Assigning a variable, what actually happens, Java
java, runtime, variable-assignment
Solution
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.
Problem
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.