Tuesday, April 16, 2013

Order of execution of Java class

Below is the order of execution of a java class

1)Static initializer block
2)main method
3)Initializer block
4)Constructor

Initializer block and Constructor will be executed only when we create an object.

public class Test {

       static
       {
              System.out.println("In static initializer block");
       }
       //Initializer block
       {
              System.out.println("In initializer block");
       }
       Test()
       {
              System.out.println("In constructor");
       }
       public static void main(String[] args)
       {
              System.out.println("In Main");
       }

}


O/P:-
In static initializer block
In Main

public class Test {

       static
       {
              System.out.println("In static initializer block");
       }
       //Initializer block
       {
              System.out.println("In initializer block");
       }
       Test()
       {
              System.out.println("In constructor");
       }
       public static void main(String[] args)
       {
              System.out.println("In Main");
              Test t = new Test();
       }
}

 O/P:-
In static initializer block
In Main
In initializer block
In constructor


No comments:

Post a Comment