Possible Duplicate:
Static Initialization Blocks
Consider the following code:
public class Test {
{
System.out.println("Empty block");
}
static {
System.out.println("Static block");
}
public static void main(String[] args) {
Test t = new Test();
}
}
We understand that first the static block would be executed followed by the empty block. But the problem is that I have never been able to understand the real utility of an empty block. Can anyone show a real example in which -
- Both static and empty blocks are being used
- Both static and empty blocks have different utilities
The static block is executed whenever your class loads. The empty block is executed whenever you instantiate your class. Try comparing these:
1.
2.
Outputs:
1.
2.
In Layman words, static block only gets called once, no matter how many objects of that type you create.
They're for two very different purposes:
Note that this question has been answered many times in stackoverflow and you would do well to search and review the similar questions and their answers. For example: static-initialization-blocks