About
Initialization block are used to initialize field with a complex logics such as:
- with a function that throw exceptions.
- check if a particular class is loaded
- only one execution with the static modifier (for a counter for instance)
Articles Related
Type
Static
static {
// whatever code is needed for initialization goes here
}
The static initialization block only gets:
- called once, no matter how many objects of that type you create.
- executed first (e.g. before your constructor and before any static methods) once the JVM loads your class.
A JDBC driver makes use of a static initializer block to register itself in the DriverManager
Dynamic
{
// whatever code is needed for initialization goes here
}
The dynamic initialization block gets called every-time a class is instantiated. They act like extensions of constructor methods.
Example
public class InitiablizationBlock {
static int myVariable;
static{
System.out.println("Static");
myVariable = 1;
}
{
System.out.println("Dynamic block");
}
public static void main(String[] args) {
InitiablizationBlock t = new InitiablizationBlock ();
InitiablizationBlock t2 = new InitiablizationBlock ();
}
}
Output:
Static
Dynamic block
Dynamic block