Skip to content
Preptima
mediumConceptCodingEntryMidSenior

Why does == sometimes work on two Integer objects and sometimes not, and where else does autoboxing catch people out?

Boxing produces objects, so == compares references. The specification requires small values to come from a cache, which is why comparisons on small numbers appear to work and fail above the cached range. The other costs are a NullPointerException on unboxing and overload resolution preferring the primitive method.

4 min readUpdated 2026-08-15Target archetype: Big Tech, Enterprise Captive, Product Startup

Answer

Short answer

Integer == Integer in Java compares object references, not numeric value. It appears to work for small values because boxing must cache integers from -128 to 127, but values outside the guaranteed cache can be different objects. Use equals() for boxed values, or unbox deliberately when you want a primitive numeric comparison.

Was this answer helpful?

Likely follow-ups

  • Why does a conditional expression that mixes Integer and int throw when the Integer is null?
  • Which wrapper types does the specification not require to be cached, and why not?
  • How would you find unnecessary boxing in a hot loop instead of guessing where it is?
  • What does Integer.valueOf give you that the deprecated constructor did not?

Related questions

Further reading