Monday, August 1, 2016

Static Block – Static Initializer - Static initialization blocks – SIB – Class intializer

While hearing ‘Static’ itself, we will be sure that the state of this will be static, ie it does not depends on object (values will not vary for each object). For accessing static things (variable, method, block, class) no need to create an instances.

SIB is used to initialize Static variables. It is execute when a class is first loaded, before loading main method. It is executed for every class loading.
This is normal block and all the code will be enclosed in {} and it should preceded with static keyword.

Syntax:
static { …………………… }

E.g
public class staticblock {

                static int i;
    int j;
    
    // start of static block
    static {
        i = 10;
  // j = 5; : compilation error :  cannot make a static reference to non-static field 'j'
        System.out.println("First static block called .........i="+i);
    }
    // end of static block
   
    staticblock(){
        System.out.println("Constructor called .......value of i....." +i);
    }
    void test() {
                staticblock.i = staticblock.i +5; // i = i+5 also correct
                System.out.println("inside method test  .......value of i....." +i);
    }
    static {
        System.out.println("Second static block .........i="+i);
    }
    public static void main(String args[]) {
                 
    System.out.println(" Main is called .....");
    System.out.println("value of satic variable from main class ..i ="+i);
                staticblock s = new staticblock();
                s.test();
                staticblock s1 = new staticblock();
                s1.test();
                staticblock.staticMethod2();
               
    }
    static {
        staticMethod();
     //test(); : compilation error:can't make refernce to non-static method
        System.out.println("Third static block.........i="+i);
    }

    public static void staticMethod() {
                i = i +5;
        System.out.println("This is static method...i="+i);
    }

    public static void staticMethod2() {
        System.out.println("This is static method2...i="+i);
    }
}


Things to know:

·         Executes before main at the time of class loading :

o   Static Block are not declared in main method. Since its loading happening before the main method, when the class is loaded into JVMi.e. initializes when class load into memory, it means when JVM read the byte code.  So the creation of static block is happening before the main method.

·         Used to initialize static data members:

o   That variables that initialized in static blocks are shared by all the objects of that class. (You can thought it like constructor of a class !!!). This block is belong to class to initialize class variables(static variables).

·         A class can have any number of static initialization blocks. And they execute in the order as they appears in the class (in source code).And can written anywhere in the program (not inside main method)

·         JVM combines all the static blocks into a single static block, as the order in that they appears in the source and then execute. If the block contain any static methods then that also execute.

·         Static blocks will be called only once at the class loading time.

·         You can’t throw checked exceptions, no return statement , can’t use this and super reference from this ‘static block’

·         JVM Limitation : static initializer block should not exceed 64K

Where to use?

·         Class has static members that requires complex initialization
·         We want check some scenarios before execution of main block. E.g to find what O.S your using(wants to develop some applications that will run alone in windows)

  • For loading drivers.
E.g You want to initialize a JDBC driver connection. This connection is constant for all over the program

static connection conn = null;
static {
try {
Class.forName("com.mysql.jdbc.Driver");
Conn = DriverManager.getConnection(url,user,password);
} catch (SQLException se) {
se.printStackTrace();
}
}

·         For Logging purpose – For initializing loggers.





No comments:

Post a Comment