Static blocks  are also called  Static initialization blocks .  A static initialization block is a normal block of code enclosed in  braces, { }, and preceded by the static keyword. Here is an example: 
 static {
    // whatever code is needed for initialization goes here
}
 A class can have any number of static initialization blocks, and  they can appear anywhere in the class body. The runtime system  guarantees that static initialization blocks are called in the order  that they appear in the source code. 
And dont forget, this code will be  executed when JVM loads the class. JVM combines all these blocks into  one single static block and then executes. Here are a couple of points I  like to mention: 
public class Test {
static {
Test.main("From static Block");
}
public static void main(String... args) {
if (args.length > 0) {
System.out.println(args[0]);
} else {
System.out.println("By JVM");
}
}
}
 
No comments:
Post a Comment