Scroll to top

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.

Author avatar
JBT
https://javabeginnerstutorial.com/

5 comments

  1. black

    Why “ananymous”? Why not “anonymous”?

  2. manoj busam

    Static block executes only when the main method is called or every time the class gets executes .

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