Understanding Static Initialization Blocks
In Java, static initialization blocks provide a special mechanism to initialize static fields within a class. Static fields are initialized only once and share the same value across all instances of a class. While it's possible to assign values to static fields within their declarations, there are certain scenarios where this approach is impractical.
Why Use Static Initialization Blocks?
Consider a situation where the value of a static field cannot be determined at the point of its declaration. For instance, imagine you have a field that represents a list of database connections, initialized based on configuration settings. You cannot directly initialize this field within its declaration because the configuration is not yet available.
In such cases, static initialization blocks come into play. These blocks are executed during class loading and provide a convenient way to initialize static fields based on the current context. They are enclosed within static curly braces:
public static class Test { static { // Initialize static fields here } }
Non-Static vs. Static Blocks
Unlike static initialization blocks, non-static blocks (also known as instance initialization blocks) are executed each time an instance of the class is created. They are used to initialize instance-specific fields or perform other setup operations.
Example
To illustrate the difference between static and non-static blocks, consider the following code:
public class Test { static { System.out.println("Static block executed once"); } { System.out.println("Non-static block executed each time an instance is created"); } public static void main(String[] args) { Test t1 = new Test(); // Non-static block executed Test t2 = new Test(); // Non-static block executed again } }
When you run this code, you will see the following output:
Static block executed once Non-static block executed each time an instance is created Non-static block executed each time an instance is created
As you can observe, the static block is executed only once during class loading, while the non-static block is executed each time an instance of the class is created.
The above is the detailed content of When and Why Use Static Initialization Blocks in Java?. For more information, please follow other related articles on the PHP Chinese website!