Wednesday, 23 August 2017

Java int += double syntax surprise




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?


Answer



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


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...