July 23, 2022

Initializer Block in Java

When you create an instance of a class, constructor is called to initialize the instance variables. An alternative to using a constructor to initialize instance variable is to use initializer block in Java. Initializer block is always executed when an instance of the class is created.

General form of Initializer block in Java

  // whatever code is needed for initialization 
  // goes here

How to use initializer block in Java

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code if you have overloaded constructors in your class. Putting the common code in an initializer block ensures that that piece of code is always executed irrespective of the constructor called.

Initializer block Java example

public class MainClass {
  //instance initializer block
    System.out.println("Instance initializer block, this block is always executed");
    System.out.println("In no-arg constructor");
  MainClass(int i){
    System.out.println("In single argument constructor-" + i);

  public static void main(String[] args) {
    MainClass obj1 = new MainClass();
    MainClass obj2 = new MainClass(10);    
Instance initializer block, this block is always executed
In no-arg constructor
Instance initializer block, this block is always executed
In single argument constructor-10

As you can see whether no-arg constructor is called or the constructor with single argument is called for initialization of the object, initializer block is always executed.

That's all for the topic Initializer Block in Java. If something is missing or you have something to share about the topic please write a comment.

You may also like

No comments:

Post a Comment