Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why static fields are not initialized in time?

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.. :/

like image 805
The Student Avatar asked Mar 30 '10 18:03

The Student


People also ask

Can we initialize static variable at the time of declaration?

If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the constructor.

Why static variables are initialized only once?

When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name.

Are static variables initialized at class loading time?

Static fields are initialized when the class is loaded by the class loader. Default values are assigned at this time.

How many times we can initialize a static variable?

Static variables can be assigned as many times as you wish. static int count = 0; is initialization and that happens only once, no matter how many times you call demo .


1 Answers

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.

like image 188
Pyrolistical Avatar answered Oct 04 '22 00:10

Pyrolistical