Primitives float and double: why f + = d does not lead to a type mismatch error?

Possible duplicate:
Java + = operator

Code example:

double d = 1; float f = 2; f += d; // no error? f = f+d; // type mismatch error, should be f = (float) (f+d); 

So, why does f+=d not produce an error (even at runtime), although it will reduce the accuracy of d ?

+4
source share
3 answers

The conditional job performs an implicit listing.

 a #= b; 

equivalently

 a = (cast to type of a) (a # b); 

Another example

 char ch = '0'; ch *= 1.1; // same as ch = (char)(ch * 1.1); // ch is now '4' 
+3
source

By JLS 15.26.2

The compound assignment expression E1 op = E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type E1, except that E1 is evaluated only once.

It means:

 f += d; 

will become

f = (float) (f+d);

+4
source

There's a good related article: Java + = and Implicit Casting

+2
source

All Articles