Java int += double syntax surprise

int, java, operators, syntax

Solution

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

Problem

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?

Original source

Related problems