The scope of a local variable declared in a block is the rest of the block, including its own initializer. The name of the local variable parameter may not be redeclared as a local variable or exception parameter within its scope, or a compile-time error occurs; that is, hiding the name of a local variable is not permitted.
A local variable cannot be referred to using a qualified name (§6.6), only a simple name.
class Test { static int x; public static void main(String[] args) { int x = x; } }
causes a compile-time error because the initialization of x
is within the scope of
the declaration of x
as a local variable, and the local x
does not yet have a value
and cannot be used.
The following program does compile:
class Test { static int x; public static void main(String[] args) { int x = (x=2)*2; System.out.println(x); } }
because the local variable x
is definitely assigned (§16) before it is used. It prints:
4
class Test { public static void main(String[] args) { System.out.print("2+1="); int two = 2, three = two + 1; System.out.println(three); } }
which compiles correctly and produces the output:
2+1=3
The initializer for three
can correctly refer to the variable two
declared in an earlier declarator, and the method invocation in the next line can correctly refer to the
variable three
declared earlier in the block.
The scope of a local variable declared in a for
statement is the rest of the for
statement, including its own initializer.
If a declaration of an identifier as a local variable 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:
class Test { public static void main(String[] args) { int i; for (int i = 0; i < 10; i++) System.out.println(i); } }
This restriction helps to detect some otherwise very obscure bugs. (A similar restriction on hiding 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.)
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:
class Test { public static void main(String[] args) { for (int i = 0; i < 10; i++) System.out.print(i + " "); for (int i = 10; i > 0; i--) System.out.print(i + " "); System.out.println(); } }
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