javavariable-assignmentcompound-operator

Java: += equivalence


Is:

x -= y;

equivalent to:

x = x - y;

Solution

  • No, they are NOT equivalent the way you expressed them.

    short x = 0, y = 0;
    x -= y;    // This compiles fine!
    x = x - y; // This doesn't compile!!!
                  // "Type mismatch: cannot convert from int to short"
    

    The problem with the third line is that - performs what is called "numeric promotion" (JLS 5.6) of the short operands, and results in an int value, which cannot simply be assigned to a short without a cast. Compound assignment operators contain a hidden cast!

    The exact equivalence is laid out in JLS 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 to clarify some of the subtleties:

    Java also has *=, /=, %=, +=, -=, <<=, >>=, >>>=, &=, ^= and |=. The last 3 are also defined for booleans (JLS 15.22.2 Boolean Logical Operators).

    Related questions