Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: += equivalence

Is:

x -= y;

equivalent to:

x = x - y;
like image 293
dukevin Avatar asked Mar 10 '10 04:03

dukevin


3 Answers

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:

  • Compound assignment expression doesn't reorder the operands
    • Left hand side stays on the left, right hand side stays on the right
  • Both operands are fully-parenthesized to ensure op has the lowest precedence
    • int x = 5; x *= 2 + 1; // x == 15, not 11
  • There is a hidden cast
    • int i = 0; i += 3.14159; // this compiles fine!
  • The left hand side is only evaluated once
    • arr[i++] += 5; // this only increments i once

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

Related questions

  • Varying behavior for possible loss of precision
  • Why doesn’t Java have compound assignment versions of the conditional-and and conditional-or operators? (&&=, ||=)
like image 61
polygenelubricants Avatar answered Nov 04 '22 11:11

polygenelubricants


Yes, it is. This syntax is the same in most C-derived languages.

like image 45
Chuck Avatar answered Nov 04 '22 13:11

Chuck


Not exactly. The reason it was introduced in C was to allow the programmer to do some optimizations the compiler couldn't. For example:

A[i] += 4

used to be compiled much better than

A[i] = A[i] + 4

by the compilers of the time.

And, if "x" has side effects, e.g "x++" then it is wildly different.

like image 27
Richard Pennington Avatar answered Nov 04 '22 13:11

Richard Pennington