Init Block and Static init Block in Java

Init block and static init block in java

  1. {  
  2.  static  
  3. }  
  4. }  
Init block gets executed every time right before the constructor.
 
Whereas static init block gets executed only once in the life of the program.
 
static init block gets executed at the time of the loading of the class in the JRE(Java Runtime Environment).
 
At the time of loading static init block executedthen searching of main starts.
//Demo for init block and static init block .
  1. class InitDemo {  
  2.  InitDemo(int x) {  
  3.   System.out.println("1-arg const");  
  4.  }  
  5.  InitDemo() {  
  6.   System.out.println("no-arg const");  
  7.  }  
  8.  static {  
  9.   System.out.println("static init block");  
  10.  } {  
  11.   System.out.println("First Instance init block");  
  12.  }  
  13.  public static void main(String[] args) {  
  14.   System.out.println("Main Started");  
  15.   InitDemo obj = new InitDemo();  
  16.   InitDemo obj2 = new InitDemo(7);  
  17.  }  
  18. }  
Output
 
Image-1.jpg