5

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 (not even at runtime), although this would decrease the accuracy of d?

Community
  • 1
  • 1
sulai
  • 5,204
  • 2
  • 29
  • 44
  • The linked dupe is for `int` and `long`, but it's the same situation here with `float` and `double`. – Mysticial Dec 11 '12 at 14:51
  • Thank you for pointing out the duplicate. I did a lot of searching, but "+=" is a bad term to search for. My apologies. – sulai Dec 11 '12 at 15:04

2 Answers2

5

As per 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.

That means:

f += d;

would become as

f = (float) (f+d);

kosa
  • 65,990
  • 13
  • 130
  • 167
4

The compount assignment does an implicit cast.

a #= b;

is equivalent to

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'
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130