Friday, February 18, 2011

Static initializer block is called only when the class is being loaded in JVM

public class StaticTest {
static {
System.out.println("Hi there");
}
public void print() {
System.out.println("Hello");
}
public static void main(String args []) {
StaticTest st1 = new StaticTest();
st1.print();
StaticTest st2 = new StaticTest();
st2.print();
}
}
So this class prints :
Hi there
Hello
Hello

Note that Hi there is printed only once.

No comments:

Post a Comment

Chitika