9

I have run into the following surprising line:

int x = 7;
x += 0.5;

is apparently legal syntax! After the addition, x is still 7, so the double is being cast to an int and rounded down to 0, but this is done without any explicit cast in the code. Is anyone else surprised by this? What's the rationale here?

edit to clarify my question: Can anyone give a good reason for this decision? It strikes me as a terrible decision to require explicit casting everywhere else, but have this one spot in the language where you silently throw away data. Am I missing something?

Eric Lindauer
  • 1,813
  • 13
  • 19

3 Answers3

14
x += 0.5;

is equivalent to:

x = (int) (x + 0.5)

In general:

x += y is equivalent to x = (type of x) (x + y)


See 15.26.2. Compound Assignment Operators

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • I understand this. What surprises is me is that the compiler allows it! In your 2nd line, there is an explicit cast, which forces the programmer to recognize that they may be losing some information. For example, x = x + .5 does not compile, but x += .5 does... strange, no? – Eric Lindauer Mar 31 '13 at 18:58
  • @EricLindauer not strange at all, `x + 0.5` yields in a double, while `(int) (x + 0.5)` is an integer. – Eng.Fouad Mar 31 '13 at 19:00
  • 2
    I guess i'm not being clear... I understand that the spec says this is how it works. My question is: WHY?? How can anyone justify allowing x += .5, but disallowing x = x + .5?! That seems crazy to me. – Eric Lindauer Mar 31 '13 at 20:36
  • @EricLindauer simply `int a = 0.5;` is invalid, while `int a = (int) 0.5` is valid. – Eng.Fouad Mar 31 '13 at 20:37
  • 2
    I think what @EricLindauer is saying is that, it should have been: `x += 0.5` should be equivilant to `x = (x + 0.5)` and do not add the part of `(int)` , since it result in silently loosing precision. – sharp12345 Mar 31 '13 at 23:03
0

x += 0.5; is the same as x = (int) (x + 0.5);.

Makoto
  • 104,088
  • 27
  • 192
  • 230
0

This is because compound assignment operators puts an implicit cast (automatic cast): So

x+=0.5 => x =(int)(x + 0.5) => x = (int)(7.5) => x = 7
Vishal K
  • 12,976
  • 2
  • 27
  • 38
  • Is there a good reason for it to do that? – Eric Lindauer Mar 31 '13 at 20:43
  • 1
    @EricLindauer: If `x` is a `short`, even if `y` is as well, a statement like `x = x + y;` would be illegal without an explicit typecast. Java thus behaves as though the result computed by any compound-arithmetic-assignment operator was explicitly typecast to the result type, whether or not it makes sense in any particular case. – supercat Feb 10 '14 at 22:34