Skip to main content
PreparationZone Logo
PreparationZone
Back to Java

Java · Medium · Free

Integer cache -128..127 — identity surprises?

JavaTrickyFresher
Model answer

Integer caching

Autoboxing converts primitives to wrappers. For Integer, Byte, Short, Character, and Long in a default range, the JVM returns cached instances—so == may be true for small values but false for larger ones.

  • Default Integer cache: -128 to 127 (configurable via -XX:AutoBoxCacheMax).
  • Always use equals or intValue() comparison for business logic.
  • new Integer(5) always new object (deprecated constructors removed in modern JDK).
  • Surprises in Map<Integer, ?> keys when mixing literals and parsed ints.
java
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b); // true (cached)
System.out.println(c == d); // false (distinct objects)
Interview tip: One-line fix—"treat boxed numbers like objects, never ==."