Java Reference
In-Depth Information
Point first;
}
Example 6.3-2. Scope of Local Variable Declarations
class Test1 {
static int x;
public static void main(String[] args) {
int x = x;
}
}
This program 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 variable
x
does not yet
have a value and cannot be used.
The following program does compile:
class Test2 {
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
In the following program, 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 cor-
rectly refer to the variable
three
declared earlier in the block.
class Test3 {
public static void main(String[] args) {
System.out.print("2+1=");
int two = 2, three = two + 1;
System.out.println(three);
}
}