(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;

yneed 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 longinto int, the IDE sees a potential error and does not allow to compile. But why does it happen in the second case?

Asked on February 4, 2020 in Programming.
Add Comment
1 Answer(s)

var1 op= var2 equivalently var1 = (T)((var1) op (var2)) , where op is an operator .


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

Answered on February 4, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.