Why do the composite assignment operators +=, -=, *=, / = in Java do not require casting?

Why do the composite assignment operators +=, -=, *=, / = in Java do not require casting?

This quick post explains why some operators need to be cast while others do not, and why.

Problem

Until today I thought that, for example:

a += b;

It was just a shortcut to:

a = a + b;

But if we try this:

int a = 2;
long b = 3;

Then the code: a = a + b; does not compile, and code a + = b compiles. Does this mean that actually a + = b; is a shortcut to something like this a = (type a) (a + b)?

Solution

Then the code: a = a + b; does not compile, and code a + = b compiles. Does this mean that actually a + = b; is a shortcut to something like this a = (type a) (a + b)?

As always with these questions, JLS has the answer. In this case, §15.26.2 Compound allocation operators. The compound assignment expression of the form E1 op = E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is an E1 type, except that E1 is only evaluated once.

Example quoted from §15.26.2

[...] the following code is valid:

short x = 3;
x + = 4.6;

and causes x to be 7 because it is equivalent to:

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

In other words, yes. The developers of the Java language have come to similar conclusions.

Share this Post