Instance block in Java

In this tutorial, we will learn about Instance block in Java. Instance blocks are used to initialize instance variables of the class. These blocks run every time when we create an object of the class. There are few things to note about instance blocks.

  • we do not right any identifier with instance block
  • instance block run every time we create an object of class
  • it is not mandatory to create instance block in each class
  • instance blocks run even before the constructor when we create an object of the class.

Example Program:

class Example{
  //Instance Block
  {
     System.out.println("This is instance block");
  }
  //Constructor
  public Example(){
     System.out.println("This is constructor block");
  }
  //main method
  public static void main(String args[]){
    Example obj=new Example();
    Example obj2=new Example();
  }
}

Output:

This is instance block
This is constructor block
This is instance block
This is constructor block

In above example you can see we have created two object of class and every time instance block is running before the constructor.

Spread the love