Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy are these == but not `equals()`?
    text
    copied!<p>I'm a bit confused about the way Java treats <code>==</code> and <code>equals()</code> when it comes to <code>int</code>, <code>Integer</code> and other types of numbers. For example:</p> <pre><code>Integer X = 9000; int x = 9000; Short Y = 9000; short y = 9000; List&lt;Boolean&gt; results = new ArrayList&lt;Boolean&gt;(); // results.add(X == Y); DOES NOT COMPILE 1) results.add(Y == 9000); // 2) results.add(X == y); // 3) results.add(X.equals(x)); // 4) results.add(X.equals(Y)); // 5) results.add(X.equals(y)); // 6) System.out.println(results); </code></pre> <p>outputs (maybe you should make your guess first):</p> <pre><code>[true, true, true, false, false] </code></pre> <ol> <li>That <code>X == Y</code> does not compile is to be expected, being different objects. </li> <li>I'm a little surprised that <code>Y == 9</code> is <code>true</code>, given that 9 is by default an <code>int</code>, and given that 1) didn't even compile. Note that you can't put an <code>int</code> into a method expecting a <code>Short</code>, yet here they are equal.</li> <li>This is surprising for the same reason as two, but it seems worse.</li> <li>Not surprising, as <code>x</code> is autoboxed to and <code>Integer</code>.</li> <li>Not surprising, as objects in different classes should not be <code>equal()</code>.</li> <li>What?? <code>X == y</code> is <code>true</code> but <code>X.equals(y)</code> is <code>false</code>? Shouldn't <code>==</code> always be stricter than <code>equals()</code>?</li> </ol> <p>I'd appreciate it if anyone can help me make sense of this. For what reason do == and equals() behave this way?</p> <p><strong>Edit:</strong> I have changed 9 to 9000 to show that this behavior is not related to the any unusual ways that the integers from -128 to 127 behave.</p> <p><strong>2<sup>nd</sup> Edit:</strong> OK, if you think you understand this stuff, you should consider the following, just to make sure:</p> <pre><code>Integer X = 9000; Integer Z = 9000; short y = 9000; List&lt;Boolean&gt; results = new ArrayList&lt;Boolean&gt;(); results.add(X == Z); // 1) results.add(X == y); // 2) results.add(X.equals(Z)); // 3) results.add(X.equals(y)); // 4) System.out.println(results); </code></pre> <p>outputs:</p> <pre><code>[false, true, true, false] </code></pre> <p>The reason, as best as I understand it:</p> <ol> <li>Different instance, so different.</li> <li><code>X</code> unboxed, then same value, so equal.</li> <li>Same value, so equal.</li> <li><code>y</code> cannot be boxed to an <code>Integer</code> so cannot be equal.</li> </ol>
 

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