Pre-increment and post-increment behavior in Java

2019-08-06 07:09发布

问题:

This question already has an answer here:

  • Is there a difference between x++ and ++x in java? 16 answers
  • Pre & post increment operator behavior in C, C++, Java, & C# [duplicate] 6 answers

Can someone explain the implementation of the following code:

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

I'm expecting the output to be 3 as explained below: Since '/' has higher precedence than '+' it is evaluated first.

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)

So the result of the '/' operation within parantheses is 2 / 2 = 1. Then comes the '+' operation:

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)

So, the result should be 3 + 1 = 4. But when I evaluate this expression, I'm getting 2. How come this happen?

回答1:

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

No, expressions are evaluated left to right - each operand is then associated using precedence rules.

So your code is equivalent to:

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