Static Block, Instance Block and Constructor: Order of Execution

Overview

In Java, we have static block, instance block and constructor which gets executed when we create an instance. All of these blocks can be used to write some initialization logic. Have you ever wondered in what sequence these blocks get executed?

First Java looks for the existence of “static blocks”. A static keyword is related to the context of the class, so that is the reason Java will execute the static blocks first. Since static blocks are related to class, you can only use static variables and static methods in it, you cannot call member variables or member methods related to the object.

If there are multiple static blocks, all of them will be executed in the order of their declaration within the class.

Then Java looks for “instance blocks”. Instance blocks are written within an open and close curly brackets. In this instance block, you can refer to non-static as well as static variables and methods.

Similar to static blocks, if there are multiple instance blocks are present, Java will execute them in the order of declaration.

Once the execution of “instance blocks” is completed, Java will execute the constructor of the class.

Example 1

In this example, you can see how Java executes static block, instance block and constructor.

package com.techstackjournal;

public class BlocksDemo {
	
	static {
		System.out.println("static block");
	}
	
	{
		System.out.println("instance block");
	}
	
	public BlocksDemo() {
		System.out.println("constructor");
	}

	public static void main(String[] args) {

		BlocksDemo bd = new BlocksDemo();
		
	}

}

Output:

static block
instance block
constructor

Example 2

In this example, you can see how Java executes when you have multiple static blocks and multiple instance blocks and a constructor.

package com.techstackjournal;

public class BlocksDemo {
	
	static {
		System.out.println("static block 1");
	}

	static {
		System.out.println("static block 2");
	}
	
	{
		System.out.println("instance block 1");
	}

	{
		System.out.println("instance block 2");
	}
	
	public BlocksDemo() {
		System.out.println("constructor");
	}

	public static void main(String[] args) {

		BlocksDemo bd = new BlocksDemo();
		
	}

}

Output:

static block 1
static block 2
instance block 1
instance block 2
constructor

Conclusion

Java executes all the static blocks first, then it will execute all the instance blocks and finally it will execute the constructor of the class.

Leave a Comment