(x = x + y) or (x + = y) – type cast differences
Faced such a property of addition. We have two variables:
int x = 1; long y = 2;
y
need to add to x
. If we use simple addition, the IDE will refuse to compile:
x = x + y; //Incopatible types
If we use the following construction:
x += y;
then the code is processed correctly.
The error is understandable – we are trying to cram long
into int
, the IDE sees a potential error and does not allow to compile. But why does it happen in the second case?
var1 op= var2
equivalently var1 = (T)((var1) op (var2))
, where op is an operator .
Example:
int x = 2; double y = 4.6;
This line is x += y;
equivalent to the bottom :
x = (int)(x + y);
Documentation: 15.26.2. Compound Assignment Operators