Organization of operator hierarchy of '+=' and '++'?

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.
Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow