Java Programs

Java Practice

Java program to implement instance initializer block

Learn how to implement instance initializer block in Java?
Submitted by Nidhi, on March 25, 2022

Problem statement

In this program, we will implement an Instance Initializer Block in a class. The IIB (Instance Initializer Block) is called when an object is getting created.

Source Code

The source code to implement the instance initializer block is given below. The given program is compiled and executed successfully.

// Java program to implement instance initializer block

class Sample {
    System.out.println("Instance initializer block called");

  Sample() {
    System.out.println("Constructor called");

public class Main {
  public static void main(String[] args) {
    Sample S = new Sample();


Instance initializer block called
Constructor called


In the above program, we created two classes Sample and Main. The Sample class contains an IIB (Instance Initializer Block) and a constructor.

In the above program, it looks like IIB is calling before the constructor. But it is not true. IIB gets called when an object is created. Java compiler copies the IIB in the constructor after the first statement super(). So constructor calls the IIB.

The Main class contains a method main(). The main() method is the entry point for the program, here we created the object of the Sample class and printed the appropriate message.

Java Instance Initializer Block Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.