Jave :Whar are “static initializers” or “static blocks with no function names”?

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 theconstructors are executed. As the name suggests they are typically used to initialize static fields.

public class StaticInitializer {
public static final int A = 5;
public static final int B; //note that it is not public static final int B = null;
//note that since B is final, it can be initialized only once.
//Static initializer block, which is executed only once when the class is loaded.
static {
if(A == 5)
B = 10;
else
B = 5;
public StaticInitializer(){} //constructor is called only after static initializer block

The following code gives an Output of A=5, B=10.

public class Test {
System.out.println("A =" + StaticInitializer.A + ", B =" + StaticInitializer.B);

No comments:

Post a Comment