Search code examples
javaconstructorstatic-initializer

Default Constructor is getting executed before Static block in java


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.


Solution

  • 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...
    }