Are you confused about the unboxing conversion?
From type
Integer
to typeint
From type
Double
to typedouble
If
r
is a reference of typeInteger
, then unboxing conversion convertsr
intor.intValue()
If
r
is a reference of typeDouble
, then unboxing conversion convertsr
intor.doubleValue()
And compound assignment operators?
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T) ((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
So this
c += a;
becomes
c = (int) (c + a);
in which case we have addition and the operands are promoted.
If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).
If either operand is of type
double
, the other is converted todouble
.
So a
becomes
a.doubleValue();
The whole expression becomes
c = (int) ((double) c + a.doubleValue()
Now, this wouldn't work if c
was an Integer
because the expression would be
c = (Integer) (c + b);
in which case c + b
is addition and the same promotion rules as before apply.
c = (Integer) ((double) c.intValue() + a.doubleValue());
but the double
value result of the addition cannot be cast to an Integer
, so it fails. Basically, don't use the compound assignment operator with wrapper (boxed) types.