我想知道为什么下面的代码返回 0。我认为 num2
在应用于 *=
之前会递增,第二行将执行 num2 = 1* 1
int num2 = 0;
num2 *= ++num2;
System.out.println(num2);
最佳答案
来自JLS :
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.
因此,您的代码相当于:
num2 = (int) (num2 * ++num2);
乘法的左侧操作数为零,因此结果为零。
关于Java 前缀运算符行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44332191/