Java Static Block: How to Write

In Java, static code blocks, defined with the static keyword, are executed only once when a class is loaded. These blocks are typically used to initialize static variables or perform operations that only need to be executed once when the class is loaded.

Here is an example of how to write a static code block:

public class MyClass {
    // 静态变量
    static int a;
    static int b;

    // 静态代码块
    static {
        // 初始化静态变量
        a = 10;
        b = 20;

        // 执行其他操作
        System.out.println("静态代码块被执行");
    }

    public static void main(String[] args) {
        // 调用静态变量
        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}

In the given code, the static block static {…} is used to initialize static variables a and b, and to print a line of information. When the MyClass class is loaded, the static block will be executed, and then the main method will access and print the values of the static variables.

The output is:

静态代码块被执行
a = 10
b = 20

Note: The execution order of static blocks is dependent on their position in the code, as they are run before initializing static variables and calling static methods.

bannerAds