Sunday, August 2, 2015

[Java] Static initialization block

Static initialization block preceded with the “static” keyword, is a block of code in braces {}.
Static {
    //do sth here
}
A class can have any number of static initialization block, no matter how many objects of that type you create and can appear anywhere in class body. The static block only gets called once no matter how many objects of that type you created, and it would be executed when class is loaded by class loader.

Example 1:

This example show static initialization block would be executed when class is loaded by class loader.
public class static1 {
    public static void main(String[] args) {}
    static {System.out.print("d ");}
}
Result 1:
d

Example 2:

The static initialization block can have any number of static initialization block, and would be executed one by one from top to bottom.
public class static1 {
    static {System.out.print("c ");}
    public static void main(String[] args) {}
   static {System.out.print("d ");}
   static {System.out.print("e ");}
   static {System.out.print("f");}
   static {System.out.print("g");}
}
Result 2:
c d e f g

Example 3: 

This example show static initialization block only gets called once no matter 3 objects of that type you created.
public class static1 {
    static {System.out.print("c ");}
    public static void main(String[] args) {
        new static1();
        new static1();
        new static1();
    }
    static {System.out.print("g ");}
}
Result 3:
c g

Reference:
http://stackoverflow.com/questions/2420389/static-initialization-blocks
http://stackoverflow.com/questions/13699075/calling-a-java-method-with-no-name

No comments :

Post a Comment