Order of execution

In this article, we will learn about the order of execution of blocks in Java.

Different blocks and their order of execution in Java Class

  1. Static Block
  2. Init Block(Anonymous Block)
  3. 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 program

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 a class gets loaded.

But Anonymous block and Constructor will run every time the object of a class gets created. Init block will get executed first and then constructor.

5 Comments

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

Leave a Reply

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.