Mastery
Mastery/Java/A. Object model, identity & memory
T1 · high-leverage

The Integer autobox cache (-128..127)

Autoboxing small int literals into Integer reuses cached instances for the range -128..127 (per the JLS, implementations may cache more but must cache at least this range). Outside that range, each boxing creates a new object, so == on boxed integers becomes an identity check that silently passes for small numbers and silently fails for larger ones — a real, recurring bug source when someone compares Integer with == instead of .equals().

java
Integer i1 = 127, i2 = 127;
Integer i3 = 128, i4 = 128;

System.out.println("127 == 127 (boxed, cached):     " + (i1 == i2));
System.out.println("128 == 128 (boxed, NOT cached): " + (i3 == i4));
System.out.println("128.equals(128):                " + i3.equals(i4));

Interview angle

A close cousin of the String == question and just as popular, specifically because autoboxing hides the object-vs-primitive distinction. Candidates who've mostly worked with primitive int and never hit a List<Integer> comparison bug in production often miss this entirely — which is exactly the gap the question is designed to surface.

In the industry

This is a real, recurring bug in code that boxes numbers into collections (List<Integer>, Map<Long, ...>) and compares with == instead of .equals()/Objects.equals(). It's especially insidious because it "works" during development and small-number testing (within the -128..127 cache) and only fails against production-scale data — a textbook "works on my machine" defect that's much harder to catch without a lint rule or a code reviewer specifically watching for boxed-type comparisons.