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
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 toE1 = (T) ((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
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.