Monday 29 August 2016

Static blocks in Java


If a class has static members that require complex initialization, a static block is the tool to use.


Unlike C++, Java supports a special block, called static block (also called static clause) which can be used for static initializations of a class. This code inside static block is executed only once: the first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class). For example, check output of following Java program.
// filename: Main.java
class Test {
    static int i;
    int j;
     
    // start of static block
    static {
        i = 10;
        System.out.println("static block called ");
    }
    // end of static block
}
class Main {
    public static void main(String args[]) {
        // Although we don't have an object of Test, static block is
        // called because i is being accessed in following statement.
//static block code execute 1st , even before constructor and main method
        System.out.println(Test.i);
    }
}
Output:
static block called
10

No comments:

Post a Comment