No it's not like that. The compound assignment operator E1 op= E2
is equivalent to E1 = (T) ((E1) op (E2))
, with the difference that E1
is only evaluated once.
From JLS 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.
So, a binary operation is performed between an Integer reference and a primitive type. In which case, the Integer reference will be unboxed, and operation will be performed, and value will again be boxed to Integer
reference. As from JLS Section 5.6.2 - Binary Numeric Promotion:
If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).
So, no a new Integer object is not necessarily created. The expression in your loop is evaluated as:
Integer sum = Integer.valueOf(sum.intValue() + i);
And the valueOf
method may use some cached value of Integer
object(for some range).
Having said all that, I hope you are not literally using a wrapper type like that in your original code, but just for the understanding purpose. You don't need to use wrapper type, unless you really need it, and that would be rare case.