Java int + = dual syntax

I came across the following amazing line:

int x = 7; x += 0.5; 

- this is apparently legal syntax! After adding x, it is still equal to 7, so the double is passed to int and rounded to 0, but this is done without any explicit cast to the code. Anyone else surprised at this? What is the rationale here?

edit to clarify my question: can anyone give a good reason for this decision? It seems to me that this is a terrible decision to require explicit casting everywhere, but there is one place in the language where you silently delete data. Did I miss something?

+7
source share
3 answers
 x += 0.5; 

equivalent to:

 x = (int) (x + 0.5) 

Generally:

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


See 15.26.2. Account Assignment Operators

+12
source

x += 0.5; matches x = (int) (x + 0.5); .

0
source

This is because complex assignment operators put an implicit cast (automatic cast): So

 x+=0.5 => x =(int)(x + 0.5) => x = (int)(7.5) => x = 7 
0
source

All Articles