Doubts about Java's +=, -=, *=, /= compound assignment operators

Compound assignment operators are:

+=、-=、*=、/=、%=、 <<=、 >>=、 >>>=、&=、 ^=和| = ;

The simple assignment operator is

= ;

In java we always think

i += j;

is a short form of

i = i + j;

But when we try to compile the code like below

int i = 5;
long j = 8;
i=i+j;
i+=j;

write picture description here

But it i=i+j;will report an error and will not compile successfully, but i+=j;will not report an error and can compile successfully

Why is this?
Does this mean that actually i+= j; such a shorthand is actually of the form i=(type of i) (i+j)?


Like this question, Java's JLS holds the answer. In this case, §15.26.2 of the JLS elaborates on compound assignment operators. extract:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.An example cited from §15.26.2

For example, the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

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


The Java Language Specification says that the compound assignment E1 op= E2 is equivalent to the simple assignment E1 =(T)((E1)op(E2)), where T is the type of E1, unless E1 is evaluated only once. In other words, compound assignment expressions automatically cast the result of the computation they perform to the type of the variable on their left. If the type of the result is the same as the type of the variable, this cast has no effect. However, if the type of the result is wider than the type of the variable, the compound assignment operator will silently perform a narrowing primitive type conversion.

Related connection
Java puzzles compound assignment and simple assignment
Java JLS official explanation on this issue

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325448825&siteId=291194637