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?

2
  • Interesting. I'm sure that the JLS addresses this though. Have you given it a look to see what it says? Commented Mar 31, 2013 at 18:55
  • @Hovercraft: The JLS gives the spec, but not the justification for the decision, which is what I'm asking about. Commented Apr 3, 2013 at 2:38

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

5 Comments

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?
@EricLindauer not strange at all, x + 0.5 yields in a double, while (int) (x + 0.5) is an integer.
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.
@EricLindauer simply int a = 0.5; is invalid, while int a = (int) 0.5 is valid.
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.
0

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

Comments

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

2 Comments

Is there a good reason for it to do that?
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.