×

Java Programs

Java Practice

Java program to implement static block with instance initializer block

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

Problem statement

In this program, we will create a class with static block, instance initializer block, and constructor.

In a Java Program, when an object gets created then the static block is called, then the constructor calls Instance Initializer Block and finishes the constructor call.

Source Code

The source code to implement static block with Instance Initializer Block is given below. The given program is compiled and executed successfully.

// Java program to implement static block with 
// Instance Initializer Block

class Sample {
  static {
    System.out.println("Static block called");
  }

  {
    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();
  }
}

Output

Static block called
Instance initializer block called
Constructor called

Explanation

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

The Main class contains a method main(). The main() method is the entry point for the program, here we created an object of the Sample class called static block, IIB, and constructor of the class.

Java Instance Initializer Block Programs »





Comments and Discussions!

Load comments ↻





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