Java: Why doesn't (int) += (double) cause a "incompatible types" error?
java, type-conversion
Solution
From JLS §15.26.2:
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.
Notice that there is a cast involved with the compound assignment. However, with the simple addition there is no cast, hence the error.
If we include the cast, the error is averted:
float a = 0;
a = (float) (a + Math.PI); // works
It's a common misconception that `x += y` is identical to `x = x + y`.
Problem
Here's an oddity: ``` float a = 0; a = a + Math.PI; // ERROR ``` and yet: ``` a += Math.PI; // OK! ``` even this works: ``` int b = 0; b += Math.PI; // OK, too! ``` Why does the `+=` operator allow lossy implicit type conversions?