The Initializer Block in Java

The Initializer block is used to declare constructors’ common parts. Let us see an example −


 Live Demo

public class Demo{
      System.out.println("The common constructor has been invoked");
   public Demo(){
      System.out.println("The default constructor has been invoked");
   public Demo(int x){
      System.out.println("The parametrized constructor has been invoked");
   public static void main(String arr[]){
      Demo my_obj_1, my_obj_2;
      System.out.println("The Demo objects have been created.");
      my_obj_1 = new Demo();
      my_obj_2 = new Demo(89);


The Demo objects have been created.
The common constructor has been invoked
The default constructor has been invoked
The common constructor has been invoked
The parametrized constructor has been invoked

A class named Demo contains a constructor without a parameter, a parameterized constructor, and the main function. Inside the main function, an instance of the Demo class is created, one with parameter, and one without parameter.