Initialization block in java

Initialization blocks as name says can be used to initialize the objects or data members in java. An initialization block contains a group of statements enclosed in a pair of braces.

Syntax : {  a group of statements }

Initialization blocks are placed within class declaration, but not  in method or constructor. It can also be considered as third place apart from method and constructor, where java operations can be performed.It is executed as if it were placed at the beginning of every constructor in the class.

Initialization blocks are of 2 types:

  1. Instance initialization block : It is executed always when an object of a class is created.
  2. Static initialization block : It has static keyword associated along with the pair of braces. This block is executed only once when the class is loaded first time. It can only initialize static data members of the class.

We will discuss about them one by one in detail.

As we know , generally we can initialize variable while declaring.

class ColorCode{
	int Red =3;
}

Simple example of initializing value by using Initialization block.

public class ColorCode {
	
	int Red;
	
	    //Constructor using the initialized value
	ColorCode(){
		System.out.println("Color code of red is "+ Red);
	}
       
        { Red=3; } // instance initialization block
	public static void main(String[] args) {
		ColorCode code = new ColorCode();    //Initialized block will be invoked

	}

}
Output : Color code of red is 3

Why do we require Initialization blocks when we can initialize fields in one line at the time of declaration of the field? 

We can go for normal initialization if we already have initialization value available and can be set in one line. But suppose, initialization requires some logic (for example, error handling or a for loop to fill a complex array), then simple assignment might not be sufficient. But this can be done in initialization block. Look at the below example for more clarification where we are performing a for loop and storing some random value in an array and same value is stored for Red color.

public class ColorCode {
	
	int Red;
	int[] CodeVal = new int[5];
	
	    // Initialization block
	    {
	        System.out.println("Start of Initializing block");
	        for(int i=0; i<CodeVal.length; i++)
	        {
	        	CodeVal[i] = (int)(100.0*Math.random());
	        }
	        Red = CodeVal[2];  // taking a random value of code
	    }
	
	    //Constructor using the initialized value
	ColorCode(){
		System.out.println("Color code of red is "+ Red);
	}

	public static void main(String[] args) {
		ColorCode code = new ColorCode();    //Initialized block will be invoked

	}

}
Output:
Start of Initializing block
Color code of red is 54
Note : Initialization block can also be used to put the common code.

Which one will invoke first – constructor or Initialization block?

Suppose, there is a constructor and an initialization block in a class. Which one will invoke first at the time of object creation?

Let’s understand with an example.

public class Library {
	
	Library(){
		System.out.println("This is a constructor");
	}
	
	{ System.out.println("This is an intialization block");}

	public static void main(String[] args) {
		
		Library lib = new Library();
	}
}
Output:
This is an intialization block
This is a constructor

By looking at the output, it seems that initialization block is executed first and then constructor. But it is not true. Actually, Constructor is executed first but  initialization block gets copied in constructor after super() keyword.

Let’s understand it with pictorial presentation.

Initialization block in java

Rules to remember for Instance Initialization block:

  1. The instance initializer block is invoked when instance of the class is created.
  2. The instance initializer block is invoked after the super() call in the constructor.
  3. The instance initializer block executes in the order in which they appear.

Let’s see how it works if multiple constructors.

class Library {
	
	Library(){
		System.out.println("This is a parent class constructor");
	}
}

class Book extends Library{
	
	Book(){
		super();
		System.out.println("Child class default constructor");
	}
	
	Book(int a){
		super();
		System.out.println("Child class parameterized constructor");
	}
	
	{ System.out.println("This is an initialization block");}

	public static void main(String[] args) {
		
		Book lib = new Book();
		Book lib1 = new Book(1);
	}
	
}
Output:
This is a parent class constructor
This is an initialization block
Child class default constructor
This is a parent class constructor
This is an initialization block
Child class parameterized constructor

Static Initialization block:

These are executed to initialize static members of the class when the class is loaded.

Rules to remember for static Initialization block:

  1. There can be any number of static blocks and can appear anywhere in the class body.
  2. The instance initializer block executes in the order in which they appear.
  3. It is executed when class is loaded.
public class ColorCodes {
	static int RedCode;
	
	static {RedCode =3;  // this will be executed without creating the object instance
		     System.out.println("color code is "+RedCode);
		   }

	public static void main(String[] args) {
		
	}

}
Output: color code is 3
Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...