Ken,
Thank you for your post. I wonder if you can extend on what you mean by scopes may be independent of each other.
Hi all,
Let's see if we can put a closure to this post. The following is directly from our Java Language Specification
http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html
Here is the part (directly from the language spec), I think (kind of) explain what we have here
If a declaration of an identifier as a local variable of the same method, constructor, or initializer block appears within the scope of a parameter or local variable of the same name, a compile-time error occurs.
Thus the following example does not compile:
This restriction helps to detect some otherwise very obscure bugs. A similar restriction on shadowing of members by local variables was judged impractical, because the addition of a member in a superclass could cause subclasses to have to rename local variables. Related considerations make restrictions on shadowing of local variables by members of nested classes, or on shadowing of local variables by local variables declared within nested classes unattractive as well. Hence, the following example compiles without error:
On the other hand, local variables with the same name may be declared in two separate blocks or for statements neither of which contains the other. Thus:
compiles without error and, when executed, produces the output:
0 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
I said "kind of" because I am still not totally sure about the following statement from the
doc
If a declaration of an identifier as a local variable of the same method, constructor, or initializer block appears within the scope of a parameter or local variable of the same name, a compile-time error occurs.
I hope someone can put in plain English. That's why I've always preferred Head First Java or Core Java over the formal Java specification
-Cheung