Home >Java >javaTutorial >Why Use Static Initialization Blocks in Java?
You might have encountered the concept of "static initialization blocks" in Java. They are meant to address scenarios where assigning values to static fields cannot be done in a single line. However, you may wonder why a special block is needed for this purpose.
In Java, non-static blocks get executed every time a new instance of the class is created. Static blocks, on the other hand, are executed only once when the class itself is initialized. This holds true regardless of how many objects of that particular class you create.
Consider the following example:
public class Test { static { System.out.println("Static"); } { System.out.println("Non-static block"); } public static void main(String[] args) { Test t = new Test(); Test t2 = new Test(); } }
Output:
Static Non-static block Non-static block
In this example, the static block containing "Static" is executed only once when the Test class is initially loaded. The non-static block containing "Non-static block" is executed every time a new instance (t and t2) of the Test class is created.
Therefore, using a static initialization block allows you to perform specific actions or assign values to static fields only once during class initialization, while non-static blocks are used for tasks that need to be performed every time an object of the class is instantiated.
The above is the detailed content of Why Use Static Initialization Blocks in Java?. For more information, please follow other related articles on the PHP Chinese website!