Why static fields are not initialized in time?

Because statics are initialized in the order they are given in source code.

Check this out:

class MyClass {
  private static MyClass myClass = new MyClass();
  private static MyClass myClass2 = new MyClass();
  public MyClass() {
    System.out.println(myClass);
    System.out.println(myClass2);
  }
}

That will print:

null
null
myClassObject
null

EDIT

Ok let’s draw this out to be a bit more clear.

  1. Statics are initialized one by one in the order as declared in the source code.
  2. Since the first static is initialized before the rest, during its initialization the rest of the static fields are null or default values.
  3. During the initiation of the second static the first static is correct but the rest are still null or default.

Is that clear?

EDIT 2

As Varman pointed out the reference to itself will be null while it is being initialized. Which makes sense if you think about it.

Leave a Comment