gpt4 book ai didi

java - 这个 Java 程序的输出

转载 作者:行者123 更新时间:2023-11-29 03:22:42 25 4
gpt4 key购买 nike

这不是我的代码,我知道这不是正确的编写方式。我在在线测试中被问到这个问题。

public class HelloWorld{

public static void main(String []args){
int x = 10;
x = x++ * ++x;
System.out.println(x);
}
}

Ouptut 是 120。我不明白为什么。不应该是 132/121 吗?是否依赖于 JVM?

最佳答案

x++ 首先被评估。它是后递增的,所以 10 是表达式的值,然后 x 递增到 11

++x 接下来被评估。它是预递增的,所以 x 递增到 1212 是表达式的值。

剩下的就是简单的乘法,10 * 12 = 120。

此行为不依赖于使用哪个 JVM;根据 Java 语言规范的规定,所有 JVM 都必须以这种方式运行。

JLS, Section 15.14.2涵盖后增量表达式:

The value of the postfix increment expression is the value of the variable before the new value is stored.

JLS, Section 15.15.1涵盖预增量表达式:

The value of the prefix increment expression is the value of the variable after the new value is stored.

关于java - 这个 Java 程序的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22725593/

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