7
int anInt = 1;
double aDouble = 2.5;

anInt = anInt + aDouble; // Error - need to cast double to int

anInt += aDouble; // This is ok. Why?

anInt = aDouble; // This is also an error.

anInt = 1 + aDouble; // This is also an error.

So my questions is: Why is it not a compile error to do anInt += aDouble?

Thirler
  • 20,239
  • 14
  • 63
  • 92

1 Answers1

8

Three of the four cases properly report an error. Compound assignment is the only exception from the rule. Java Language Specification, part 15.26.2, explains why:

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.

For example, the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);

As you can see, the error is avoided by implicit insertion of a cast.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Yes. I came across it in my code and was just surprised the compound assignment didn't need a cast. Thanks for the answer. – Tony Narvarte Mar 04 '15 at 16:09