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?
From JLS §15.26.2:
A compound assignment expression of the form
E1 op= E2is equivalent toE1 = (T) ((E1) op (E2)), whereTis the type ofE1, except thatE1is 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With