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:
++i
, i
is 2 then;+=
, i = i + 2
, at this time point, I thought i
should be 4 now, but the result is 3.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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With