The += operator in Java


Until now, I thought that the entry

i += j;

Is the same as

i = i + j;

However, if we take

int i = 5;
long j = 8;

That expression i = i + j is not compiled, while i += j will compile without problems.

Does it mean that i += j is equivalent to something like i = (type of i) (i + j)?

Author: Kyubey, 2015-04-17

1 answers

The answer can be found in the Java specifications, §15.26.2 Compound Assignment Operators:

The assignment of the form E1 op= E2 is equivalent to the expression E1 = (T) ((E1) op (E2)), where T is the type E1. The only difference is that E1 is evaluated only once.

Next, there is the following example:

This code is correct:

short x = 3;
x += 4.6;

As a result, we get the value 7 for x, since this is equivalent to:

short x = 3;
x = (short)(x + 4.6);

In other words, your guesses are correct.

 20
Author: Vadik, 2020-06-12 12:52:24