title: Java: Integer equals vs. ==
body: <p>As of Java 1.5, you can pretty much interchange <code>Integer</code> with <code>int</code> in many situations.</p>
  
  <p>However, I found a potential defect in my code that surprised me a bit.</p>
  
  <p>The following code:</p>
  
  <pre><code>Integer cdiCt = ...;
  Integer cdsCt = ...;
  ...
  if (cdiCt != null &amp;&amp; cdsCt != null &amp;&amp; cdiCt != cdsCt)
      mismatch = true;
  </code></pre>
  
  <p>appeared to be incorrectly setting mismatch when the values were equal, although I can't determine under what circumstances. I set a breakpoint in Eclipse and saw that the <code>Integer</code> values were both 137, and I inspected the boolean expression and it said it was false, but when I stepped over it, it was setting mismatch to true.</p>
  
  <p>Changing the conditional to:</p>
  
  <pre><code>if (cdiCt != null &amp;&amp; cdsCt != null &amp;&amp; !cdiCt.equals(cdsCt))
  </code></pre>
  
  <p>fixed the problem.</p>
  
  <p>Can anyone shed some light on why this happened? So far, I have only seen the behavior on my localhost on my own PC. In this particular case, the code successfully made it past about 20 comparisons, but failed on 2. The problem was consistently reproducible.</p>
  
  <p>If it is a prevalent problem, it should be causing errors on our other environments (dev and test), but so far, no one has reported the problem after hundreds of tests executing this code snippet.</p>
  
  <p>Is it still not legitimate to use <code>==</code> to compare two <code>Integer</code> values?</p>
  
  <p>In addition to all the fine answers below, the following stackoverflow link has quite a bit of additional information. It actually would have answered my original question, but because I didn't mention autoboxing in my question, it didn't show up in the selected suggestions:</p>
  
  <p><a href="https://stackoverflow.com/questions/2602636/why-cant-the-compiler-jvm-just-make-autoboxing-just-work">Why can't the compiler/JVM just make autoboxing “just work”?</a></p>