static variable load process
-
21-12-2019 - |
Question
Recently, I research how virtual machine load static variable, but I encounter a problem as follows:
public class Example{
static{
num = 3;
System.out.print(num);
}
public static int num;
}
The compiler reports an error. I think the num
has memory area and value. Why can't I access num
variable?
Solution
static
blocks and declarations are executed in the order they are coded. This means that at the time the static block executes, the num
field is not yet defined.
The simple fix is moving the declaration above the block.
The Java Language Specification Section 8.3.2.3 (among other things) says that a variable may assigned a value before being declared, but the value of the variable may not be accessed before the variable is declared unless its name is fully qualified, so this compiles:
public class Example {
static{
num = 3; // assignment OK without qualifying the name
System.out.print(Example.num); // name must be qualified to access value
}
public static int num;
}
Still more interesting is that if a variable is accessed before being declared, its default value is used, and further the initialization on declaration still occurs, so this code:
public class Example {
static{
System.out.println(Example.num); // uses default value
num = 3; // assignment OK
System.out.println(Example.num); // assigned value (3) is visible
}
public static int num = 1; // initialization to 1 occurs
static{
System.out.print(Example.num); // initialized value (1) is visible
}
}
Produces this output:
0
3
1
Wow!