Search code examples
javaprimitiveinteger-arithmeticcompound-assignment

Confusion about compound assingnments (+=, -=, *=, ...) in Java


I'm a little confused about the result of the following code:

    int x = 1;
    x -= ((x += 1) << 1);
    System.out.println(x);

It prints out -3, but I'd expected it to print out -2, because in my head the computation should go like this:

| Opearation | Returned | x |
+------------+----------+---+
| int x = 1; |     -    | 1 |
+------------+----------+---+
| (x += 1)   |     2    | 2 |
+------------+----------+---+
| (2 << 1)   |     4    | 2 |
+------------+----------+---+
| x -= 4;    |     -    |-2 |

What am I missing here? Can somebody please explain to me what's going on?

Thanks!


Solution

  • JLS 15.26.2 says following, https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.26.2

    If the left-hand operand expression is not an array access expression, then:

    First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.

    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.

    Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (§5.1.13) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.

    So the original value of x, i.e. 1, is saved, then the RHS is evaluated. Therefore it's -3.