refresh java logo

Static and Instance Initializer blocks

Initializer block is a block of code defined inside curly brackets { }. These blocks are defined inside a class but outside the method. These blocks are generally used to initialize variables but we can use normal statements as well as we do in methods.

Generally we assign an initial value to a variable like below :

 class Test  { 
     // count is initialized to 10   
     int count = 10;
   }         

This approach works well when you know the initial value. If initialization requires some logic (for example some conditional statements or exception handling), this approach is not sufficient. That is where initialization blocks are quite useful. There are two types of initializer blocks in java :

  • Static initializer block or Static block
  • Non static or instance initializer block

Static initializer block

A static initializer block is a block of code defined inside curly bracket { } preceded by static keyword. These blocks are generally used to initialize static or class variables. A static initializer block is also known as static block. The syntax of declaring a static block is :

 class ClassName
   {         
     static {
        // Initialization code     
       }
   }               

Some key points about static initializer blocks are :

  • A class can have multiple static blocks.
  • These blocks can appear anywhere in class body.
  • These blocks are executed in the order they appear in the program.
  • These blocks are executed only once.
  • These blocks belongs to class not objects.

When does static blocks are executed ?

As soon as your class is loaded by java virtual machine, all static blocks given inside your class is executed. static blocks are executed even before main method is called.

Java program of static block

 class StaticBlockDemo {	     
    static double result;    
   
    static {
        result = Math.pow(2,3);
        System.out.println("First static block, result = "+ result);
      }
    static {
        result = Math.log10(100);          
        System.out.println("Inside second static block, result = "+ result);
      }
    public static void main(String [] args) {            
        System.out.println("Inside main method");
      }             
 } 

Output:

First static block, result = 8.0
Inside second static block, result = 2.0
Inside main method

As you can see from the output, static blocks are executed from top to bottom. It is executed even before main method is executed. This program uses Math class of java which provides different methods for different mathematical calculations.

Can we run a program having static block only, no main method.

It depends on the version of java you are using. Prior to JDK 7 you can run a program having static block only, no main method. But from JDK 7 and above you can not run a program without main method.

When we should use static block ?

When you want to execute something that needs to be executed before any method of the class is executed, you should use static blocks. Generally static blocks are used to initialize static variables that requires some sort of operation or need to access some method.

Instance initializer block

Instance initializer block is a block of code defined inside { }. As the name suggests, these blocks are generally used to initialize instance variables. The syntax of declaring instance initializer block is :

 class ClassName
   {    
        // Instance initializer block
      {
         // Initialization code
      }
   }         

Some key points about instance initializer blocks are :

  • A class can have multiple instance initializer blocks.
  • These blocks can also appear anywhere in class body.
  • These blocks are executed in the order they appear in the program.
  • Instance initialization blocks run every time a new instance is created.
  • At compilation time, compiler copies instance block code and place at the beginning of all constructors just after the call of super class constructor.
  • These blocks run just after the super class constructor has completed execution and before the start of current class constructor.
  • They can be used to perform operations those are common to constructors.

Java program of instance initializer block

 class InstanceBlockDemo { 
    int ivar;
    public InstanceBlockDemo() {
        System.out.println("Inside constructor");  
     } 
     // First initializer block
     {
       ivar = 20;
       System.out.println("First initializer block");  
     } 
     // Second initializer block
     {
       System.out.println("Second initializer block");  
     }  
    public static void main(String args[]) {   
       InstanceBlockDemo ibd = new InstanceBlockDemo();
       System.out.println("Inside main method"); 
       System.out.println("ivar = "+ibd.ivar);    
     }     
  }  

Output:

First initializer block
Second initializer block
Inside constructor
Inside main method
ivar = 20 

As mentioned above, after compilation java compiler places all initializer block code inside each constructor, so after compilation the above constructor will contains the code like below :

 public InstanceBlockDemo() {
    super();    
    { 
      ivar = 20;
      System.out.println("First initializer block"); }
    }  
    { 
      System.out.println("Second initializer block"); 
    } 
    System.out.println("Inside constructor");  
 }       

Why we should use instance initializer block ?

We know that we can initialize instance variables which requires some operation or logic inside a constructor, then question comes that why we should use this block. Sometimes we need to perform some common initialization in multiple constructors. In such cases it's better to write these common code inside an instance initializer block rather than writing in multiple constructors, since compiler itself places this code inside each constructor.

Which initializer block runs first, static or non static initializer block ?

Static initialization blocks always runs before instance initializer block since they are executed during the class initialization itself.

The program given below contains both static and non static block. It demonstrates the execution order of static and non static blocks.

Java program of static and non static block

 class InitializerBlock { 
    // constructor
    public InitializerBlock() {
         System.out.println("Inside constructor");  
       }  
     {
       System.out.println("First instance initializer block");  
     } 
     {
       System.out.println("Second instance initializer block");  
     }     
     static {
          System.out.println("First static block");
      }
     static {         
          System.out.println("Second static block");
        }
         
    public static void main(String args[]) {   
       InitializerBlock in = new InitializerBlock();
       System.out.println("Inside main method");  
     }     
  }  

Output:

First static block
Second static block
First instance initializer block
Second instance initializer block
Inside constructor
Inside main method