ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.