1

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 Answers1

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
assylias
  • 321,522
  • 82
  • 660
  • 783
  • OK. But, then I cannot understand the meaning of the operator presedence in the following page: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html – Karşıbalı Mar 03 '15 at 12:12
  • @Karşıbalı each "sub expression" (`j--`, `++j`, `j++`) is evaluated from left to right. Once each sub expression has been evaluated, they are "combined" based on the precedence rule, so that `temp 2 / temp3` is calculated and then added to `temp1` - without the predence rules, `temp1` would be added to `temp2` and the result would be divided by `temp3`... – assylias Mar 03 '15 at 12:19