java - 这个 Java 程序的输出

标签 java output

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

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/

相关文章:

Java 将 2D 图形作为参数传递

c - 防止c中输出字符重复

java - Android Wear bundle 通知和背景图片

java - 空格作为第一个字符读取文件java

c 程序正在编译和运行,但我在终端中得到一个奇怪的输出

C++ std::cout 十六进制

Haskell - putStr 与 putStrLn 和指令顺序

java - 在运行时在 log4j.xml 中添加和删除记录器

java - JTable 行颜色取决于模型中的值?

java - 尝试 mvn 包时出现 mvn 包错误