4

Consider the following:

int a = 1;
double b = 0.5;
System.out.println(a += b);    // case x
System.out.println(a = a + b); // case y

What is immediately apparent is that the above does not even compile - case y will fail due to "incompatible types". If I run case x by itself, it will simply return a.

What is going on here? Does the shorthand operator (+=) "catch" the failed assignment and default to simply returning the lhand value? If that is so, is it really correct to claim that the a += b is equivalent to a = a + b, as is very common in tutorials?

csvan
  • 8,782
  • 12
  • 48
  • 91
  • 6
    This was mentioned before http://stackoverflow.com/questions/8710619/java-operator. It has pretty elaborate answer there. โ€“ sve Nov 07 '13 at 21:24
  • 2
    That is not true. His problem is not related to not understanding the += operation. It is related to type issues (Integer vs. double). Reopen please. โ€“ Philipp Jahoda Nov 07 '13 at 21:32
  • @PhilippJahoda The Integer vs double problem was discussed here http://stackoverflow.com/questions/2696812/varying-behavior-for-possible-loss-of-precision . And here http://stackoverflow.com/questions/15733184/java-int-double-syntax-surprise?lq=1 . And here http://stackoverflow.com/questions/8272635/why-does-java-perform-implicit-type-conversion-from-double-to-integer-when-using ... โ€“ sve Nov 07 '13 at 21:36

2 Answers2

6

According to Java Language Specification, section 15.26.2, compound assignment operators insert an implicit conversion to the type of the left-hand side operand:

The result of the binary operation is converted to the type of the lefthand 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.

An assignment a = a + b would require a cast to be equivalent:

a = (int)(a + b);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

You have a double and int value:

a += b is equivalent to a = (int)(a + b);
a = a + b is equivalent to a = a + b;

in the latter you can't compile because you are trying to add a double to an int without casting. a += b does the cast for you.

Arash Saidi
  • 2,228
  • 20
  • 36