Default Constructor is getting executed before Static block in java

343 Views Asked by At

When we load a class in java, first static block get executed and then default constructor. but in below peace of code, What I observed that default constructor is getting executed before static block.

    public class Hello {

    private static Hello hello = new Hello();

    public Hello() {
        System.out.println("Hello Default Constructor");
    }

    static {
        System.out.println("Hello Static Block");
    }

    public static Hello createHelloInstance() {
        return hello;
    }
}

Main Class:

   public class MainTest {

        public static void main(String a[])
        {
            Hello.createHelloInstance();
        }
    }

Output:

Hello Default Constructor
Hello Static Block

I need to know the fundamental concept behind that. what is that so happening. ? Could someone help me to understand the flow behind that.

3

There are 3 best solutions below

0
On BEST ANSWER

You have a static member (hello) which is initialized with a new Hello() call that calls the default constructor. Since this member is declared before the static block, it will be initialized first. If you move it after the block, the block will be executed first:

public class Hello {
    static {
        System.out.println("Hello Static Block");
    }
    private static Hello hello = new Hello();

    // etc...
}

Or better yet, make the order explicit by moving the initialization inside the block.

public class Hello {
    private static Hello hello;
    static {
        System.out.println("Hello Static Block");
        hello = new Hello();
    }

    // etc...
}
0
On

IN the same way instance field initialiser expressions are inserted into constructors, static field initialiser expressions are inserted into the static initialiser in order of appearance.

So

private static Hello hello = new Hello();

...

static {
    System.out.println("Hello Static Block");
}

Is the equivalent of:

private static Hello hello;

...

static {
    hello = new Hello();
    System.out.println("Hello Static Block");
}
0
On

Yes, but you have this line of code:

private static Hello hello = new Hello();

and that is reason why you have constructor executed first. Static initializers are executed before constructor.