Java中的Postfix和Prefix运算符表现不同

时间:2017-08-22 06:49:22

标签: java operators prefix postfix

基于Oracle:Operator Doc Oracle

postfix incr和decr运算符的首选项高于prefix运算符。

但是当我尝试这个例子时:

int x = 1;
System.out.println(++x * x++); // prints 4

x=1;
System.out.println(x++ * ++x); // prints 3

如果我们作为运算符优先级,输出应为:3 and 3而不是4 and 3

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

这只是post / pre increment元素:

(++x * x++);
++x = 1 becomes 2 and use 2 for value
x++ = use 2 for value, and then 2 becomes 3
2*2 = 4
(x++ * ++x);
x++ = use 1 for value, and then 1 becomes 2
++x = 2 becomes 3 and use 3 for value
1*3 = 3

预增量:递增值并使用新值进行计算

后增量:记住旧值,用于此计算,然后递增