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?