When objects created with static reference, why do instance block & default constructor get executed before static block?

public class TestLab {

    static Test aStatic=new Test();
    public static void main(String[] args) {

        TestLab obj=new TestLab();
    }
    static{
        System.out.println("In static block of TestLab");
          }

}


public class Test {


    static Test ref=new Test();
    Test()
    {
        System.out.println("Default Constructor of Test");
    }
    static
    {
        System.out.println("In Static Block of Test");
    }
    {
         System.out.println("In instance block of Test");
    }

}

Normally the static blocks are executed first during class loading. When the above example is executed, the following output is received:

In instance block of Test

Default Constructor of Test

In Static Block of Test

In instance block of Test

Default Constructor of Test

In static block of TestLab

Why does the instance block and Default Constructor of Test class gets executed before the static block of Test Class?

Jon Skeet
people
quotationmark

When the type is initialized, all the static initializers and all the static field initializers are executed, in textual order. From JLS 12.4.2:

Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

In other words, this code gets executed:

ref = new Test();
System.out.println("In Static Block of Test");

That first line creates an instance... which requires the instance initializer to be run. All of that instance initialization happens before control returns to the type initialization part - i.e. before the line from the static initializer runs.

If you move the field declaration to after the static initializer, you'll see the opposite results.

people

See more on this question at Stackoverflow