The Initializer Block in Java

Course Curriculum

The Initializer Block in Java

The Initializer Block in Java

Initializer block contains the code that is always executed whenever an instance is created. It is used to declare/initialize the common part of various constructors of a class. For example,

import java.io.*;
public class Prutor
{
// Initializer block starts..
{
// This code is executed before every constructor.
System.out.println("Common part of constructors invoked !!");
}
// Initializer block ends

public Prutor()
{
System.out.println("Default Constructor invoked");
}
public Prutor(int x)
{
System.out.println("Parametrized constructor invoked");
}
public static void main(String arr[])
{
Prutor obj1, obj2;
obj1 = new Prutor();
obj2 = new Prutor(0);
}
}
Output:

  • Common part of constructors invoked!!
  • Default Constructor invoked
  • Common part of constructors invoked!!
  • Parametrized constructor invoked
    We can note that the contents of initializer block are executed whenever any constructor is invoked (before the constructor’s contents)

The order of initialization constructors and initializer block doesn’t matter, initializer block is always executed before constructor. See this for example.

Static blocks in Java (Prev Lesson)
(Next Lesson) Instance Initialization Block (IIB) in Java
', { 'anonymize_ip': true });