Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java int += double syntax surprise [duplicate]

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?

like image 310
Eric Lindauer Avatar asked Mar 31 '13 18:03

Eric Lindauer


1 Answers

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

like image 190
Eng.Fouad Avatar answered Oct 10 '22 18:10

Eng.Fouad