On JDK 23 two boxed 128s are not ==, a Map of Long keys misses an int lookup and List.remove(1) removes by index. javac -Xlint:all warns about none of them.
A comparison that passed every test
Geetha's stock service at Belgavi's Book Store compares two Integer quantities with ==: the quantity reserved for an order and the quantity confirmed by the warehouse. Unit tests used quantities like 1, 3 and 12, and passed. In production a bulk order for 200 copies of a textbook never matched its confirmation, and the order sat in a review queue.
The values were equal. The comparison was not between values. == on two Integer references asks whether they are the same object, and autoboxing produces the same object only for small values. Java has several related traps where boxed numbers behave differently from primitives. This article reproduces them on JDK 23.0.2 with a small probe that prints one line per check.
The Integer cache decides what == returns
Autoboxing an int calls Integer.valueOf. Its JDK 23 documentation says the method will always cache values in the range -128 to 127, inclusive, and may cache other values outside that range. The probe boxes the same value twice and compares:
| Value | a == b | a.equals(b) |
|---|---|---|
| 100 | true | true |
| 127 | true | true |
| 128 | false | true |
| 1000 | false | true |
| -128 | true | true |
| -129 | false | true |
Long.valueOf documents the same guarantee for -128 to 127, and the probe agrees: two boxed 127L values are identical, two boxed 128L values are not. The Java Language Specification, section 5.1.7, requires identical results for boxing constant expressions in that small range and nothing beyond it, so code that relies on == above 127 is relying on an implementation detail that may change.
That detail is adjustable, which makes things worse. On HotSpot the flag -XX:AutoBoxCacheMax=2000 enlarges the Integer cache; with it the probe prints true for 128 and 1000. Long is unaffected: 128L == 128L stays false. A test environment and a production environment with different JVM flags can therefore disagree about the same line of code.
The javac compiler does not help here. The probe is compiled with -Xlint:all and produces no warning for any of the patterns in this article. Static analysers such as Error Prone or IDE inspections do flag reference comparison of boxed types, which is a good reason to run one in the build.
The fix is to compare values: a.equals(b) when neither can be null, Objects.equals(a, b) when either can, or Integer.compare(a, b) == 0. Better still, keep quantities as int in the domain model and box only at collection boundaries.
A Long key looked up with an int
The service keeps titles by order id in a Map<Long, String>. Elsewhere the order id arrives as an int:
Map<Long, String> titlesByOrder = new HashMap<>();
titlesByOrder.put(1201L, "Atlas of Rivers");
int orderId = 1201;
titlesByOrder.get(orderId); // null
titlesByOrder.get((long) orderId); // "Atlas of Rivers"
titlesByOrder.containsKey(orderId); // falseMap.get takes an Object, so the compiler boxes orderId to an Integer, and Integer.equals returns false for any Long, even with the same numeric value. The probe confirms Integer.valueOf(1201).equals(Long.valueOf(1201)) is false. There is no compile error and no warning; the lookup just misses.
The same happens with remove and contains on collections of Long. Fix it at the boundary: convert ids to the map's key type once, preferably into a small value type such as an OrderId record, so that the compiler rejects the wrong type outright.
List.remove(int) removes by position
List has two remove methods: remove(int index) removes the element at a position, and remove(Object o) removes the first element equal to o. With a List<Integer>, overload resolution picks remove(int) for an int argument without boxing:
Call on [1, 5, 3] | Result |
|---|---|
remove(1) | [1, 3], the element at index 1 |
remove(Integer.valueOf(1)) | [5, 3], the value 1 |
remove(3) | IndexOutOfBoundsException |
Code that means "remove the quantity 3 from this list" throws, or silently removes the wrong element when the list happens to be long enough. Write remove(Integer.valueOf(x)) when you mean the value, or use removeIf(q -> q == x) with a primitive comparison inside.
Unboxing null throws
Unboxing a null reference throws NullPointerException. The probe shows two forms:
Map<String, Integer> stock = new HashMap<>();
int onHand = stock.get("BB-ISBN-0001"); // NullPointerException
Integer q = useDefault ? 0 : stock.get("BB-ISBN-0001"); // NullPointerException tooThe second surprises people. When one operand of the conditional operator is an int and the other an Integer, the expression has type int, so the Integer branch is unboxed even though the result is assigned back to an Integer. Use stock.getOrDefault(key, 0), or make both operands the same boxed type.
Comparators and equality in sorting code
A comparator written as (x, y) -> x.getSold() == y.getSold() ? 0 : ... with Integer getters returns non-zero for equal values above 127, which breaks the comparator's contract and can make TreeMap lookups miss or sorts throw. The probe's final line shows 1000 == 1000 false for boxed values while Integer.compare returns 0 and Objects.equals returns true. Use Comparator.comparingInt(Book::getSold), which compares primitives.
Records, generics and the same trap in new code
Newer language features do not remove the trap; they move it. A record declared as record StockLine(String isbn, Integer quantity) gets an equals that calls Objects.equals on each component, which is correct, but your own code that compares line.quantity() == other.quantity() is not. Generic code is affected too: a method <T> boolean same(T a, T b) { return a == b; } compiles for any type and silently compares references for boxed numbers. And streams box by default: list.stream().map(Book::getSold) produces a Stream<Integer>, while mapToInt(Book::getSold) produces an IntStream of primitives, which is both correct for == and cheaper.
Project Valhalla proposes value classes, which could change identity semantics for some JDK classes in a future release. Nothing in JDK 23 does, and code written today should not depend on it.
Why the cache exists at all
The cache saves allocation for the small numbers programs use most, such as loop counters, flags and small quantities. It is a performance measure that the specification constrains only for the small range. Treat any equality that holds because of it as accidental.
Verification
- Write tests with values outside -128 to 127, and with ids larger than
Integer.MAX_VALUEwhere ids arelong. Most of these bugs pass any test that uses small numbers. - Run tests with the same JVM flags as production, or at least without
AutoBoxCacheMax. - Add a test that looks up a
Map<Long, V>with a value built from anintrequest parameter, and one that removes a value from aList<Integer>by value; both fail loudly once written, and both are the kind of line a reviewer reads past. - Run the companion probe on each JDK you deploy to and diff its output against the recording.
- Add a static analysis rule for reference comparison of boxed types and for collection calls with an argument of the wrong boxed type.
- Prefer primitive streams and primitive-specialised collections in hot paths; besides correctness, they avoid allocation for values outside the cache.
Failure modes in review
==between anIntegerfield and a value read from JSON or a database driver, which usually returns boxed objects.Map<Long, ...>keyed by database ids, queried with anintfrom a request parameter.List<Integer>.remove(x)in code that manages quantities or positions.- Ternaries mixing
intliterals with nullableIntegerlookups. - Equality in
equalsandhashCodeimplementations that compare boxed fields with==.
The companion example prints each check and compares the output with a recording from JDK 23.0.2, so it can be rerun on another JDK to see which lines change.