Java 中的预增量和 post 增量行为

Pre-increment and post-increment behavior in Java

谁能解释一下下面代码的实现:

int j = 1;
System.out.println(j-- + (++j / j++));

我希望输出为 3,如下所述: 由于“/”的优先级高于“+”,因此首先对其进行评估。

op1 = ++j (Since it is pre-increment, the value is 2, and j is 2)
op2 = j++ (Since it is post-increment, 2 is assigned and j is incremented to 3)

所以括号内'/'运算的结果是2 / 2 = 1。 然后是'+'操作:

op1 = j-- (Since it is Post-increment, the value is 3, and j is decremented to 2)
op2 = 1 (The result of the '/' was 1)

所以,结果应该是 3 + 1 = 4。 但是当我计算这个表达式时,我得到 2。这是怎么发生的?

Since '/' has higher precedence than '+' it is evaluated first.

不,表达式是从左到右计算的 - 然后使用优先规则关联每个操作数。

所以你的代码等同于:

int temp1 = j--; //1
int temp2 = ++j; //1
int temp3 = j++; //1
int result = temp1 + (temp2 / temp3); //2