Java: Initialization blocks

In this article, we will learn and understand the importance of initialization blocks in Java

And we’ll look into why they are needed in Java, when we can initialize values directly or through constructor while creating objects

Initialization blocks are block of code within {curly braces} where we can initialize initial or default values for variables or to perform complex operations using Java logics

There are 2 types of Initialization blocks,

  • Static Initialization blocks
  • Instance Initialization blocks

We will go through each one with detailed example

 

Static initialization blocks

Static initialization blocks are bundle of valid Java statements within {curly braces} preceded/prefixed with “static” keyword

Syntax of Static initialization blocks

static {
	// bundle of valid Java statements
	// for initialization for static data member
}

Note: Static initialization blocks are also known as “static initializer” or “static blocks

 

Key points about Static blocks:

  • Static blocks are executed at the time of class loading
  • And these static blocks are executed only once i.e.; at the time of class loading
  • It is used to initialize static data members or class variables only
  • Any number of static blocks can be created inside class body
  • But if there are multiple static blocks, then these are executed in the order they are defined
  • Just lines of Java statements with no arguments or return values
  • Static methods can be invoked from static blocks i.e.; within {curly braces}
  • As static blocks are belongs to classes rather objects, therefore this and super keyword cannot be used
  • Static blocks can throw unchecked exception only like RuntimeException

 

Why static blocks are important in Java?

Generally, we can initialize static data members or class variables directly but sometimes we may require some operation needs to be performed before assigning/initializing a static data member for which we have flexibility of static blocks in Java

Here, operation means some Java logic execution inside static blocks

 

Example on Static blocks:

StaticBlocksInJava.java

package in.bench.resources.constructor.example;

public class StaticBlocksInJava {

	// static block 1 - after class declaration
	static {
		System.out.println("static block 1 - after class declaration");
	}

	// static data members
	static int id;
	static String name;

	// default constructor
	StaticBlocksInJava() {
		System.out.println("StaticBlocksInJava >> inside default constructor");
	}

	// static block 2 - after static members declaration
	static {
		System.out.println("static block 2 - after default constructor");
	}

	//	main() method - entry point to JVM
	public static void main(String[] args) {
		System.out.println("main() method - entry point to JVM");
		StaticBlocksInJava sblk = new StaticBlocksInJava();
	}

	// static block 3 - after main() method
	static {
		System.out.println("static block 3 - after main() method");
	}
}

Output:

static block 1 - after class declaration
static block 2 - after default constructor
static block 3 - after main() method
main() method - entry point to JVM
StaticBlocksInJava >> inside default constructor

 

Explanation:

In this example,

  • All static blocks gets executed first i.e.; even before control goes to main() method
  • Once static blocks are completed execution then control goes to main() method where it prints simple message and
  • Later create instance of the same class à which invokes default no-arg constructor and prints simple message
  • Finally, program terminates

 

Instance initialization blocks (Non-static blocks)

Instance initialization blocks are bundle of valid Java statements within {curly braces}

Syntax of Instance initialization blocks

{
	// bundle of valid Java statements
	// for initialization of instance data member and complex operation 
}

Note: Instance initialization blocks are also known as “instance blocks” or “instance initializers

 

Key points about Instance blocks:

  • Instance initializers are belongs to instance i.e.; instance blocks are executed every time object is created using new keyword
  • Instance blocks are used to initialize instance data members of class
  • Both constructor and instance blocks are related to object. So what is their order execution?
  • Instance blocks gets executed just after the constructor’s super() call and then constructor gets executed
  • It means, instance blocks are executed in between super constructor call and current object’s constructor
    diagram here
  • Any number of instance blocks can be created inside class body
  • But if there are multiple instance blocks, then these are executed in the order they are defined

 

Why instance blocks are important in Java?

Generally, constructor are used to initialize instance data members in Java but sometimes it is required to add some complex operation before assigning any values to these instance data members

So, we can perform these complex operations inside instance blocks within {curly braces}

This way, Java logic inside instance blocks gets executed before the execution of current class’s constructor and resulting value can be assigned to instance data members

 

Example on Instance blocks:

InstanceBlocksInJava.java

package in.bench.resources.constructor.example;

public class InstanceBlocksInJava {

	// instance block 1 - after class declaration
	{
		System.out.println("instance block 1 - after class declaration");
	}

	// static data members
	int id;
	String name;

	// default constructor
	InstanceBlocksInJava() {
		System.out.println("InstanceBlocksInJava >> inside default constructor");
	}

	// instance block 2 - after static members declaration
	{
		System.out.println("instance block 2 - after default constructor");
	}

	//	main() method - entry point to JVM
	public static void main(String[] args) {
		System.out.println("main() method - entry point to JVM");
		InstanceBlocksInJava iblk = new InstanceBlocksInJava();
	}

	// instance block 3 - after main() method
	{
		System.out.println("instance block 3 - after main() method");
	}
}

Output:

main() method - entry point to JVM
instance block 1 - after class declaration
instance block 2 - after default constructor
instance block 3 - after main() method
InstanceBlocksInJava >> inside default constructor

 

Explanation:

In this example,

  • When program execution starts, simple message gets printed from main() method
  • After that, it creates object of the same class à which invokes default constructor
  • But before the execution of current class’s constructor, super class’s constructor gets executed i.e.; lang.Object class in this example
  • After super class’s constructor execution, all instance in the order they are defined are executed
  • Later current class’s constructor gets executed
  • Which means instance blocks are executed between super class’s constructor and current class’s constructor
  • Finally, program terminates

 

References:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.6

 

Read Also:

Happy Coding !!
Happy Learning !!

Java: Constructors, Initialization blocks and their execution order
Java 8: Interface interview question and answers