class Hello12 {
static int b = 10;
static {
b = 100;
}
}
class sample {
public static void main(String args[]) {
System.out.println(Hello12.b);
}
}
On running above code the output comes as 100 because when I called Hello class, static block is executed first setting the value of b to 100 and displaying it. But when i write this code:
class Hello12 {
static {
b = 100;
}
static int b = 10;
}
class sample {
public static void main(String args[]) {
System.out.println(Hello12.b);
}
}
Here the output comes as 10. I am expecting answer as 100 because once the static block is executed it gave b the value as 100. so when in main(), I called Hello.b it should have referred to b (=100). How is the memory allocated to b in both the codes?
Statics are evaluated in the order they appear in the program.
Besides answering the question of how the code is executed in what order, I am guessing you also want to know why a static block can refer to a static variable that has not been textually declared/executed yet.
While section 12.4.2 of the JLS does explain that static blocks and static variable are executed in the textual order that they appear, section 8.3.3 of the JLS explains when you can reference what, and you can see that the condition of
The use is not on the left hand side of an assignment;
fails, allowing your static block in the second example to refer to a static variable that has not textually in order been declared/executed yet.Static blocks and static variables are initialized in the order in which they appear in the source. If your code is:
The result is 100.
In the "Detailed Initialization Procedure" for classes, Section 12.4.2 of the JLS states:
This means that it's as if the first example was:
And the second example was:
The last assignment "wins", explaining your output.