A static initializer block is executed when the class that contains it is initialized - which is normally when the class is loaded.
You would say that the JVM should load and initialize class Hello
when you access Hello.x
in class Test4
. However, that doesn't happen here, because this is a special case.
static final
constants are inlined by the compiler - which means that when this code is compiled, the Hello.x
in the main
method is replaced at compilation time by the value of the constant, which is 10
. Essentially, your code compiles to the same byte code as when you would compile this:
class Test4 {
public static void main(String[] args) {
System.out.println(10); // Inlined constant value here!
}
}
class Hello {
final static int x = 10;
static {
System.out.println("Hello");
}
}
Note that class Test4
doesn't really access class Hello
in this case - so class Hello
is not loaded and the static initializer is not executed when you run Test4
.