Static fields are initialized during the initialization "phase" of the class loading (loading, linking and initialization) that includes static initializers and initializations of its static fields. The static initializers are executed in a textual order as defined in the class.
Consider the example:
public class Test {
static String sayHello() {
return a;
}
static String b = sayHello(); // a static method is called to assign value to b.
// but its a has not been initialized yet.
static String a = "hello";
static String c = sayHello(); // assignes "hello" to variable c
public static void main(String[] arg) throws Throwable {
System.out.println(Test.b); // prints null
System.out.println(Test.sayHello()); // prints "hello"
}
}
The Test.b prints null
because when the sayHello
was called in static scope, the static variable a
was not initialized.