gpt4 book ai didi

java - 声明时初始化变量值

转载 作者:行者123 更新时间:2023-12-02 04:10:18 25 4
gpt4 key购买 nike

有人可以解释一下为什么下面的程序会产生 100 吗?我预计 1010

public final class Testing {
static int j = function1();
static int i = 10;

public static void main(String[] args) {
System.out.println(i);
System.out.println(j);
}

public static int function1() {
return i;
}

}

最佳答案

static 变量按照它们在类源代码中出现的顺序进行初始化。因此当j初始化时,i默认还是0,所以function1返回0 code> 和 j 初始化为 0

j初始化为0后,i初始化为10,并且您的main 打印 100

JLS 12.4.2 :

Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

关于java - 声明时初始化变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33865036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com