我试图了解以下输出为 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 toE1 = (T) ((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
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/