In the following example what actually happens?
int a = 1;
a += (a = 2);
The output is 3, however I wanted to know what actually happens under the covers.
For example i know that parentheses have higher priority to +
so happening first (a = 2) the expression should become a = 2 + 2
.
At runtime first the expression within parentheses should be executed and then a becomes 2. It seems that the first a
on the left to +
gets "loaded" before of (a = 2)
and this last expression does not seem to override the previous loading.
In other words I am quite confused to what exactly happens behind the scenes.
If anybody knows, thanks a lot in advance.
From the JLS section §15.26.2 Compound Assignment Operators:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
So for your example we have:
a = (a) + (a = 2)
With the expression evaluated left to right. Hence the output of 3
See the referenced example 15.7.1-2 from http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.7.1, which is almost identical to the example you provided. In particular:
If the operator is a compound-assignment operator (§15.26.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied binary operation.
Because of this precedence, the left hand of the += is evaluated first.
It might be confusing to you because of the parentheses, but note the section on parenthesis evaluation: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.7.3, and in particular:
The Java programming language respects the order of evaluation indicated explicitly by parentheses and implicitly by operator precedence.
In this case, the implicit precedence set by the += operator indicates that the left hand operand will be remembered per the spec. While it's true that assignment operators, including "+=" have lowest precedence, the spec for += indicates that the left-hand operand will be remembered per 15.26.2.
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