Order of execution

Here we will learn to see the order of execution of blocks in Java.

Different block  and their order of execution Java Class

  • Static Block
  • Init Block(Anonymous Block)
  • Constructor
/*
 * Here we will learn to see how the different part (Ananymous Block, Constructor and Static Block ) of class will behave
 * and what would be the order of execution. 
 */
class JBTCLass {

	/*
	 * Here Creating the Ananymous Block
	 */
	{
		System.out.println("Inside Ananymous Block");
	}

	/*
	 * Now Creating the Static Block in Class
	 */
	static {
		System.out.println("Inside Static Block");
	}

	/*
	 * Here Creating the Constructor of Class
	 */
	JBTCLass() {
		System.out.println("Inside Constructor of Class");
	}

	public static void main(String[] args) {

		// Creating the Object of the Class
		JBTCLass obj = new JBTCLass();

		System.out.println("*******************");

		// Again Creating Object of Class
		JBTCLass obj1 = new JBTCLass();

	}

}

The output of the above programme

Inside Static Block
Inside Ananymous Block
Inside COnstructor of Class
*******************
Inside Ananymous Block
Inside COnstructor of Class

As you can see STATIC block will execute only once when class gets loaded.

But Anonymous block and Constructor will run every time object of a Class gets created.

<< Write Hello World program using Eclipse Access Modifiers in Java >>

5 Comments Order of execution

    1. J Singh

      Static block gets executed when class is loaded. It has nothing to do with mains method. When ever main method is called. Class gets loaded hence this behaviour.

      Reply

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.