Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Variables, Data Types & Operators

Why can comparing two Integer objects with == sometimes return true and sometimes false?

Level II · JuniorVariables, Data Types & Operators
Short answer

Integer caches boxed values from -128 to 127 (the IntegerCache), so == on two autoboxed values in that range compares the same cached reference and returns true.

Explanation

Outside that range each autoboxing creates a new object, so == returns false even when the numeric values are equal. The lesson is to always use .equals() or unbox to int before comparing, and to never rely on identity for boxed numbers.

Common mistakes
  • Using == to compare Integer objects; it only works by accident for cached values -128..127.
  • Not realising auto-unboxing a null Integer throws NullPointerException.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Variables, Data Types & Operators.

Practise free

More on Variables, Data Types & Operators