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 -
Static initializer block is executed when class is loaded into memory, while instance initializer block is executed when an instance of the object is created using the new() operator.
Java 8Object Oriented ProgrammingProgramming. Instance variables are initialized using initialization blocks. However, the static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded.
Therefore, only one time static block will be executed. Note: Instance block and constructor both are executed during the object creation but instance block will execute first before the execution of the constructor during the object creation.
Yes. It is possible to define multiple static blocks in a java class.
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
The static block is executed whenever your class loads. The empty block is executed whenever you instantiate your class. Try comparing these:
1.
public static void main(String[] args) {
Test t = new Test();
}
2.
public static void main(String[] args) {
}
Outputs:
1.
Static block
Empty block
2.
Static block
In Layman words, static block only gets called once, no matter how many objects of that type you create.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With