4

I am a little confused about the following short code snippet, why is the result not 4, but 3?

int i = 1;
i += ++i;
System.out.println(i);

What I thought is:

  1. Calculate the right side, ++i, i is 2 then;
  2. Calculate the +=, i = i + 2, at this time point, I thought i should be 4 now, but the result is 3.
Oliver
  • 147
  • 9

2 Answers2

10

Calculate the right side, ++i

No, that's not the first step.

The first step is to evaluate the original value of the left side. Then evaluate the right side. Sum them, and assign the result to the variable.

So

i += ++i;

is broadly equivalent to

i = i + (++i);

In particular, from JLS 15.26.2, emphasis mine:

  • Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

  • Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I think the ++ operator has a higher precedence than +=, why is the ++ operation not done first? – Oliver Sep 09 '17 at 19:47
  • 2
    @WenhuCao: Precedence is about grouping. It's precedence that means `a + b * c` is treated as `a + (b * c)` rather than `(a + b) * c` - but `a` would still be evaluated first. – Jon Skeet Sep 09 '17 at 19:48
  • OK, let me digest for a while... Thanks a lot anyway:) – Oliver Sep 09 '17 at 19:52
5

The Evaluation Order is as:

i += ++i;

=> i = i + ++i;  
=> i = 1 + ++i;
=> i = 1 + 2;

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

Naman
  • 27,789
  • 26
  • 218
  • 353