Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Why doesn't (int) += (double) cause a "incompatible types" error? [duplicate]

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?

like image 883
Aleksandr Dubinsky Avatar asked Nov 29 '13 22:11

Aleksandr Dubinsky


1 Answers

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.

like image 111
arshajii Avatar answered Oct 01 '22 09:10

arshajii