Until now, I thought that writing
i + = j;
is the same as
i = i + j;
However, if you take
int i = 5;
long j = 8;
That expression i = i + j
will not compile, while i + = j
will compile without problem.
Does i + = j
mean something like i = (type of i) (i + j)
?
Answer 1, authority 100%
The answer can be found in the Java specs, ยง15.26.2 Compound Assignment Operators :
Assignment of the form
E1 op = E2
is equivalent to the expressionE1 = (T) ((E1) op (E2))
, where T is the type of 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 7 for
x
, as this is equivalent to:short x = 3; x = (short) (x + 4.6);
In other words, your guesses are correct.