Can someone help me understand the scoping rules in Java? This is clearly not valid:
{
int i = 0;
System.out.println(i); // fine, of course
}
System.out.println(i); // syntax error
i
is declared within the {}
, and it's not available outside. So what about this:
for (int i = 0; i < 10; i++) {
System.out.println(i); // fine, of course
}
System.out.println(i); // syntax error, same as above.
I'm surprised at the syntax error here. i
is declared in the outer scope yet it is not available later on. Is it bound to the inner block scope by some special rule for for
loops? Are there other scenarios where this can happen?
It's the defined behavior of the
for
loop in Java.Source: http://download.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Yes, this is exactly the case.
There's obviously the local variable declaration:
See also:
From the language specification.
think of for loop actually represented like this: