Monday, 25 April 2016

What are Static initializers or Static blocks ?


A static initializer block resembles a method with no name, no arguments, and no return type.
There is no need to refer to it from outside the class definition.

Syntax
static {
   // CODE
}

When a class is loaded, all blocks that are declared static and don’t have function name (i.e. static initializers) are executed even before the constructors are executed.


They are typically used to initialize static fields.
Here, parameters don't make any sense, so a static initializer block doesn't have an argument list.


Example

public class StaticInitilaizer {
  public static final int A= 5;
  public static final int B; 
  // Static initializer block, 
  //  which is executed only once when the class is loaded.
  static {
        if(A == 5)
           B = 10;
        else
           B = 5;
  }

  // constructor is called only after static initializer block
  public StaticInitilaizer() { }
}

Using the class

System.out.println("A =" + StaticInitilaizer.A 
                    + ", B =" + StaticInitilaizer.B);


Output
A=5, B=10

No comments:

Post a Comment

Note: only a member of this blog may post a comment.