Static block in Java

By | April 29, 2020

In this tutorial, we will learn about Static block in Java. A very important thing about the static block is the static block belongs to class not to instance. That’s why static block only runs once it doesn’t matter how many numbers of instance we create. There are few things to note about the static block in Java.

  • We do not use any identifier with static block but we use static keyword.
  • Static block only runs once.
  • Static block can even run even without creating an object of the class.
  • Static block runs before the constructor and instance bock of the class.

Example Program

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

Output:

This is static block

As you can see we haven’t even created a single object of the class still our static block is running. Here is another example to show what if we will create constructor and instance blocks in class.

Example Program

public class Example{
  //Static Block
  static{
     System.out.println("This is static block");
  }
  //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[]){
      new Example();
      new Example();
      new Example();
  }
}

Output:

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

As you can see in above example static block is only running once. On the other hand instance block and constructor running three time because we have created three objects of class.