Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>No it's not like that. The compound assignment operator <code>E1 op= E2</code> is equivalent to <code>E1 = (T) ((E1) op (E2))</code>, with the difference that <code>E1</code> is only evaluated once.</p> <p>From <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2" rel="nofollow">JLS Section 15.26.2</a>:</p> <blockquote> <p>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.</p> </blockquote> <p>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 <code>Integer</code> reference. As from <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2" rel="nofollow">JLS Section 5.6.2 - Binary Numeric Promotion</a>:</p> <blockquote> <p>If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).</p> </blockquote> <p>So, no a new Integer object is not necessarily created. The expression in your loop is evaluated as:</p> <pre><code>Integer sum = Integer.valueOf(sum.intValue() + i); </code></pre> <p>And the <code>valueOf</code> method may use some cached value of <code>Integer</code> object(for some range).</p> <hr /> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload