Java program to initialize instance data member using instance initializer block

Learn how to initialize instance data member using instance initializer block in Java?
Submitted by Nidhi, on March 26, 2022

Problem Solution:

In this program, we will create a class that contains an Instance Initializer Block, which is used to initialize Instance data members.

Program/Source Code:

The source code to initialize Instance Data Member using Instance Initializer Block is given below. The given program is compiled and executed successfully.

// Java program to initialize Instance Data Member 
// using Instance Initializer Block

class Sample {
  int num;

  //Instance Initializer Block
  {
    num = 200;
  }

  //Constructor    
  Sample() {
    System.out.println("Num is: " + num);
  }

}

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

Output:

Num is: 200

Explanation:

In the above program, we created two classes Sample and Main. The Sample class contains an instance member num, and Instance Initializer Block to initialize data members. It also contains 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.