View RSS Feed

Java Object

Static Initialization Blocks

Rate this Entry
by , 04-26-2012 at 05:53 PM (951 Views)
A static initialization block is considered to be a normal code block which is enclosed in braces, { }. It is however preceded, by the static keyword. For example:
Java Code:
static {
    // whatever code is needed for initialization goes here
}
A class may consist of any static initialization blocks number.They might be present in the class body, anywhere. It is guaranteed by the runtime system to call static initialization blocks in similar order in which they are preent in source code.

Alternatively, one might write the private static method:

class Whatever {
public static varType myVar = initializeClassVariable();

private static varType initializeClassVariable() {

// initialization code goes here
}
}
[/code]
The private static methods advantage is that one might use them later on if reinitialization of the class variable is required.

Submit "Static Initialization Blocks" to Facebook Submit "Static Initialization Blocks" to Digg Submit "Static Initialization Blocks" to del.icio.us Submit "Static Initialization Blocks" to StumbleUpon Submit "Static Initialization Blocks" to Google

Categories
Tutorial

Comments