Difference between a += 10 and a = a + 10 in java?

java, variable-assignment

Solution

As you've now mentioned casting... there is a difference in this case:

byte a = 5;
a += 10; // Valid
a = a + 10; // Invalid, as the expression "a + 10" is of type int

From the Java Language Specification section 15.26.2:

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.

Interestingly, the example they give in the spec:

short x = 3;
x += 4.6;

is valid in Java, but not in C#... basically in C# the compiler performs special-casing of += and -= to ensure that the expression is either of the target type or is a literal within the target type's range.

Problem

Are `a += 10` and `a = a + 10` both the same, or is there some difference between them? I got this question while studying assignments in Java.

Original source

Related problems