java如何初始化静态变量和静态方法?(附简单代码)

How java initialize static variables and static method?(with simple code)

我想知道 java 如何初始化这些静态变量。 我看不懂的代码如下所示:

public class Main {

static int first=test();
static int second=2;
static int third=test();

public static void main(String[] args) {

    System.out.println(first);
    System.out.println(second);
    System.out.println(third);

}


public static int test() {
    return second;
}

}

The output of the simple code below is 0 2 2

如果编译器会自动忽略不可执行的方法或静态变量在定义之前为0?

抱歉找不到对 google 的准确描述。

当Java执行代码时是从上到下。因此,当它初始化变量时,它会从上到下进行。但是,当您读取单位化值时,它将是 0nullfalse,因为内存首先用零填充。注意:class 的静态字段有自己的特殊对象,您可以在堆转储中看到它。

所以当你尝试设置

first = 0; // second hasn't been set yet
second = 2;
third = 2; // second has been set to 2.

添加该方法只会阻止编译器在变量初始化之前检测到您正在尝试使用该变量。

这可能对你有帮助。

// executing order top to bottom
static int first=test();//test() will return value of second still second is 0
static int second=2;//now second will be 2
static int third=test();//test() will return current value of second, which is 2

public static void main(String[] args) {

    System.out.println(first);// so this will be 0
    System.out.println(second); // this will be 2
    System.out.println(third); // this will be 2

}

public static int test() {
    return second;
}

您可以通过在其中放置一些打印语句来测试编译器是否忽略了不可执行的方法

public static int test() {
    System.out.println("Test exceuted")
    return second;
}

现在你的输出可能是:

Test exceuted
Test exceuted
0
2
2

这向我们表明该方法已执行,但因为第二次尚未初始化它 returns 0 第一次。

让我们尝试从 JVM 的角度来理解事物:

Loading - JVM 查找具有特定名称的类型 (class/interface) 的二进制表示,并从该二进制表示创建 class/interface。 静态成员(变量/初始化块)在 class 加载期间加载 - 按照它们在代码中出现的顺序。

此处,作为加载的一部分 - 静态成员按出现顺序执行。方法 test() 被调用了两次;但是第一次,变量 second 只是声明,没有定义(初始化)——因此默认为 0。之后,它得到值 2 并打印 - 0 2 2.

尝试在代码中放置一个静态块并放置一些调试点 - 您会自己看到的。