Why static fields are not initialized in time?

initialize static field
initializing static member java
initialize static int java
static variable initialization jvm
static variable in a class is initialized when
are static variables initialized
reading static variable during its initialization
instantiate static variable

The following code prints null once.

class MyClass {
   private static MyClass myClass = new MyClass();
   private static final Object obj = new Object();
   public MyClass() {
      System.out.println(obj);
   }
   public static void main(String[] args) {}
}

Why are the static objects not initialized before the constructor runs?

Update

I'd just copied this example program without attention, I thought we were talking about 2 Object fields, now I saw that the first is a MyClass field.. :/


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.

When are static variables initialized?, This single initialization procedure is run automatically, one time only, when the class is first loaded. In case of inner classes, they can not have  Why are the static objects not initialized before the constructor runs? Update I’d just copied this example program without attention, I thought we were talking about 2 Object fields, now I saw that the first is a MyClass field..


Let's try a different way to explain this...

This is the sequence the JVM goes through when you first reference the class MyClass.

  1. Load the byte-code into memory.
  2. Memory for the static storage is cleared (binary zero).
  3. Initialize the class:
    1. Execute each static initializer in the order that it appears, this includes static variables and static { ... } blocks.
    2. JVM then initializes your myClass static variable to a new instance of MyClass.
    3. When this happens, the JVM notices that MyClass is already loaded (byte-code) and in the process of being initialized, so it skips initialization.
    4. Allocate memory on heap for object.
    5. Execute constructor.
    6. Print out value of obj which is still null (since it is not part of the heap and constructor initialized variables).
    7. When constructor finishes, execute next static initializer which sets obj to a new instance of Object.
  4. Class initialization done. From this point, all constructor calls will behave as you presume/expect - that is obj would not be null but a reference to an Object instance.

Remember that Java specifies that a final variable is assigned a value once. It is not that it is guaranteed to be assigned a value when the code references it unless you ensure that the code references it after it is assigned.

This is not a bug. This is the defined way to handle usage of the class during its own initialization. If this were not so, then the JVM would go into an infinite loop. See step #3.3 (if the JVM does not skip initialization for a class that is in the process of initialization it would just keep initializing it - infinite loop).

Note as well, this all happens on the same thread that first references the class. Second, the JVM guarantees that initialization will complete before any other thread is allowed to use this class.

Initialization of static variables in C, A static filed/variable belongs to the class and it will be loaded into the memory But if you declare an instance variable static and final Java compiler will not initialize it in the If you don't a compile time error is generated. In case of inner classes, they can not have static fields. An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (§8.7) or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields”


That's because Java executes the static section in order it is declared. In your case, the sequence is

  1. new MyClass
  2. new Object

When #1 is executed, obj is still not initialized, so it prints null. Try the following and you will see the difference:

class MyClass {
  private static final Object obj = new Object();
  private static MyClass myClass = new MyClass();
  public MyClass() {
    System.out.println(obj); // will print null once
  }
}

Generally speaking, it is better to avoid such a construct all together. If you are trying to create a singleton, that's how that code fragment should look like:

class MyClass {

  private static final MyClass myClass = new MyClass();

  private Object obj = new Object();

  private MyClass() {
    System.out.println(obj); // will print null once
  }
}

Can i initialize static variable after the initialization?, Compile time error. DefaultExample.java:2: error: variable name not initialized in the default constructor static final String name; ^ DefaultExample  C# language specification makes it pretty clear that static fields are initialized only once, before the class is first used: The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration.


that is because static fields initialized in same order they defined.

Java Static Method, Variable and Block with Example, That is, a final static variable declared but not given a value or not initialized is known as the static block and initializing the USER_ID at the time of declaration. First, the class will be marked as initialized. Then the first static field will be initialized with a new instance of MyClass(). Note that myClass is immediately given a reference to a blank MyClass instance. The space is there, but all values are null.


@Pyrolistical

since the initial of first static field myclass is not fully constructed ...the result i get is

null null testInitialize.MyObject@70f9f9d8 null

Do static variables get initialized in a default constructor in java?, The tactic of initializing a static field the first time it is used, known as "lazy field volatile : double-checked locking by itself is not correct under  The standard guarantees two things - that objects defined in the same translation unit (usually it means .cpp file) are initialized in order of their definitions (not declarations): 3.6.2. The storage for objects with static storage duration (basic.stc.static) shall be zero-initialized (dcl.init) before any other initialization takes place.


Can we initialize static variables in a default constructor in Java?, To provide the same capability for class variables, the Java programming language includes static initialization blocks. Note: It is not necessary to declare fields at  If a static constructor exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class. A local variable is not automatically initialized and thus has no default value.


Static and non static blank final variables in Java, Static initialization is guaranteed to occur at some time before any static fields are accessed but not before a static method or instance  When To Use Static Classes In C#. The static modifier in C# declares a static member of a class. The static modifier can be used with classes, properties, methods, fields, operators, events, and constructors, but it cannot be used with indexers, finalizers, or types other than classes.


Incorrect lazy initialization of a static field - Java queries, class SomeClass { static boolean b; static byte by; static char c; static However, the reverse is not legal: you cannot initialize a class field to  As you can see, a static initializer is similar to an initializer block but begins with the word static. As with an initializer block, you code static initializers in the class body but outside any other block, such as the body of a method or constructor. The first time you access a static member such as a static field or a static method, any