Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There is a difference. The first will be treated as </p> <pre><code>Integer I = Integer.valueOf(30); // autoboxing </code></pre> <p>which will use an <code>Integer</code> object already stored in an internal cache (this is true when autoboxing values in the range -127 to 128 inclusive). The second will explicitly create a <em>new</em> <code>Integer</code> object.</p> <p>You can see this for yourself:</p> <pre><code>Integer I1 = 30; Integer I2 = 30; System.out.println(I1 == I2); </code></pre> <pre> true </pre> <p>vs</p> <pre><code>Integer I1 = new Integer(30); Integer I2 = new Integer(30); System.out.println(I1 == I2); </code></pre> <pre> false </pre> <p>In general don't compare <code>Integer</code> objects with <code>==</code> since that tests for reference equality. I was using it here to test if <code>I1</code> and <code>I2</code> refer to the same instance. In the first snippet, they do because the <code>Integer</code> corresponding to the <code>int</code> <code>30</code> already exists in a cache, and this instance is used and assigned to both <code>I1</code> and <code>I2</code>. In the second snippet, they do not since we are creating two independent objects via <code>new</code>.</p> <p>By the way there is no autoboxing involved in the second case, you're just creating a simple new object. There is autoboxing in the first case because an <code>int</code> is being implicitly converted to an <code>Integer</code>.</p> <p>You can actually see the effects of autoboxing by viewing the compiled bytecode with <code>javap -c MyClass</code>.</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