+= 和++(预增量)的 Java 运算符优先级

标签 java operator-precedence

我试图了解以下输出为 5 的 Java 代码的求值顺序:

int a = 1;
a += 2 + ++a;
System.out.println(a);

我对运算符优先级(最高列在前)的理解是:

++ 2
+ 4
+= 14

来自这个列表

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

当最终运算符被求值(+=)时,+=的求值开始时a的值不就是2吗?

最佳答案

JLS says the following about the compound assignment operator +=

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

所以+=用在了

int a = 1;
a += 2 + ++a;

相当于

int a = 1;
a = (int) ((a) + (2 + ++a));

填空,这就变成了

a = 1 + (2 + 2);

关于+= 和++(预增量)的 Java 运算符优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25613580/

相关文章:

java - 如何切换 double 是否为负数?

java - 找到正确的代码: Array of jTextField

haskell - 制作串联 Haskell 变体 : precedence of application and composition

javascript - && 和 ||在 Javascript 中的相同表达式中

c - 在 C 中打印 boolean 结果

java - Java 中的视频缩略图

java - Java-使用现有的公钥文件加密字符串

java - JPA 将 native 查询结果映射到非实体 DTO

Python代码评估顺序?

c - arr[0] = arr[1] = C 中的值是不好的做法吗?