Wednesday, August 11, 2010

Static vs init block in java

The static block is only loaded when the class object is created by the JVM for the 1st time whereas init {} block is loaded every time class object is created. Also first the static block is loaded then the init block.

public class LoadingBlocks {

static{
System.out.println("Inside static");
}
{
System.out.println("Inside init");
}
public static void main(String args[]){
new LoadingBlocks();
new LoadingBlocks();
new LoadingBlocks();
}
}
Output:
Inside static
Inside init
Inside init
Inside init

1 comment:

  1. Nice post however i am not convinced by this "The static block is only loaded when the class object is created by the JVM for the 1st time whereas init {} block is loaded every time class object is created. Also first the static block is loaded then the init block"


    static block is executed only once whenever that class is loaded by the classloader not when the class object.

    did you mean the Class object or the class's object?

    ReplyDelete