25 October, 2012

Initialization Block Vs Static Block in Java

Static does not need any object to execute. Before creating any object the static block can execute as we are using in static method. So, here the static block is call at the time of JVM execution , means before creating the object( when first time JVM execute ). But Initialization block is   call/loaded every time when object is created.Whenever the object is created at that time the Initialization block is loaded.

Example :- Sample Code

package manoj.experiment;
/**
  * @author MANOJ
 *
 */
public class InitBlockStaticBlock {

    /*
     * Static block
     */
    static{
        System.out.println("I am here in static");
    }
   
    /*
     * INIT block
     */
    {
        System.out.println("I am here in INIT ");
    }
   
    /**
     * @param args
     */
    public static void main(String[] args) {
        InitBlockStaticBlock obj1=new InitBlockStaticBlock();
        InitBlockStaticBlock obj2=new InitBlockStaticBlock();
        InitBlockStaticBlock obj4=new InitBlockStaticBlock();

    }

}


Out put :-
I am here in static
I am here in INIT
I am here in INIT
I am here in INIT