Sunday, June 7, 2009

Static Initialization Blocks & their alternatives


Static Initialization Blocks and their alternatives in Java

Why do we need Static Initialization Blocks?


The easiest way of initializing fields (static or instance) in Java at the time of their declaration is simply by providing a compile time constant value of a compatible data type. For example:



public class InitializationWithConstants{

public static int staticIntField = 100;
private boolean instanceBoolField = true;

}


This type of initialization has its limitation due to its simplicity and it can not support initialization based even on some moderately complex logic - like initializing only selected elements of a complex array using some logic in a for loop.

Here comes the need for static initialization blocks and initializer blocks for initializing static and instance fields, respectively.


Static Initialization Blocks - what are they and how to use them?


It's a normal block of code enclosed within a pair of braces and preceded by a 'static' keyword. These blocks can be anywhere in the class definition where we can have a field or a method. The Java runtime guarantees that all the static initialization blocks are called in the order in which they appear in the source code and this happens while loading of the class in the memory.



public class InitializationWithStaticInitBlock{

public static int staticIntField;
private boolean instanceBoolField = true;

static{
//compute the value of an int variable 'x'
staticIntField = x;
}
}


Since static initialization blocks are actually code-blocks so they will allow us to initialize even those static fields which require some logical processing to be done for them to get their initial values.


Alternative to Static Initialization Blocks


A private static method is a suitable alternative to the static initialization blocks. In fact it has some advantages over static initialization blocks as well like you can re-use a private static method to re-initialize a static field in case you need it. So, you kind of get more flexibility with a private static method in comparison to the corresponding static initialization block. This should not mislead that a 'public' static method can't do the same. But, we are talking about a way of initializing a class variable and there is hardly any reason to make such a method 'public'.
More about how to pick the access control modifiers here - Choosing a suitable access control modifier >>


public class InitializationWithPrivateStaticMethod{

public static int staticIntField = privStatMeth();
private boolean instanceBoolField = true;

private static int privStatMeth() {
//compute the value of an int variable 'x'
return x;
}
}


Liked the article? Subscribe to this blog for regular updates. Wanna follow it to tell the world that you enjoy GeekExplains? Please find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


No comments: