Sub topic 6
The wrapper cache and the == surprise
This chapter assumes you know Java's primitive types, how == and equals differ on objects, and what autoboxing does at a basic level. Here you will see why == on two Integer variables can return true for one value and false for another. You will also see what the cache behind that behavior is, which wrapper types have one, and how to write comparisons that never depend on it.
The surprise
Run this program on a default JVM:
public class CacheSurprise {
public static void main(String[] args) {
Integer a = 127;
Integer b = 127;
System.out.println(a == b); // true
Integer c = 128;
Integer d = 128;
System.out.println(c == d); // false
}
}The two pairs are written the same way. Only the value differs, and the result flips. The reason is that == on two reference-typed operands compares object identity. It does not compare numeric value. The two Integer variables are == only when they point to the same object. Whether they do depends on where the objects came from.
Where the objects come from
Autoboxing a value compiles to a call to Integer.valueOf(int). That method does not always allocate a new object. Its contract allows it to return a shared instance. The method works roughly like this:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high) {
return IntegerCache.cache[i + (-IntegerCache.low)];
}
return new Integer(i);
}This is a simplified version of the JDK source. IntegerCache is a private nested class. When it is initialized, it creates one Integer object for each value from -128 to 127 and keeps them in an array. Every call to valueOf with a value in that range returns an object from this array. Any value outside the range gets a fresh object on each call.
So Integer a = 127; Integer b = 127; makes both variables point to the same cached object, and a == b is true. For Integer c = 128; Integer d = 128;, each boxing allocates its own object. The variables point to different objects, and c == d is false.
Which wrapper types are cached
Not every wrapper class has a cache. The table shows what the JDK does in the common implementation. The Java Language Specification (JLS 5.1.7) only guarantees part of this.
| Wrapper | What `valueOf` caches | Guaranteed by the JLS? |
|---|---|---|
| `Boolean` | Both values, `TRUE` and `FALSE` | Yes |
| `Byte` | All 256 values | Yes |
| `Short` | -128 to 127 | Yes |
| `Integer` | -128 to 127 (the upper bound can be raised) | Yes, for -128 to 127 |
| `Character` | 0 to 127 | Yes |
| `Long` | -128 to 127 | No, but the JDK does it |
| `Float` | Nothing | No |
| `Double` | Nothing | No |
The JLS requires the cache for the values listed as guaranteed. It does not forbid caching more. This means a JVM may return true for c == d above, and your program must not depend on either answer.
This program shows several of these types side by side:
public class CacheTour {
public static void main(String[] args) {
Integer i1 = 127, i2 = 127;
Integer i3 = 128, i4 = 128;
System.out.println("Integer 127: " + (i1 == i2)); // true
System.out.println("Integer 128: " + (i3 == i4)); // false
Integer m1 = -128, m2 = -128;
Integer m3 = -129, m4 = -129;
System.out.println("Integer -128: " + (m1 == m2)); // true
System.out.println("Integer -129: " + (m3 == m4)); // false
Long l1 = 127L, l2 = 127L;
Long l3 = 128L, l4 = 128L;
System.out.println("Long 127: " + (l1 == l2)); // true
System.out.println("Long 128: " + (l3 == l4)); // false
Character c1 = 'a', c2 = 'a';
Character c3 = '\u0100', c4 = '\u0100';
System.out.println("Character 'a': " + (c1 == c2)); // true
System.out.println("Character U+0100: " + (c3 == c4)); // false
Boolean b1 = true, b2 = true;
System.out.println("Boolean true: " + (b1 == b2)); // true
Double d1 = 1.0, d2 = 1.0;
System.out.println("Double 1.0: " + (d1 == d2)); // false
}
}The outputs in the comments are what a default HotSpot JVM prints. The Double case shows the point most clearly. Even the value 1.0 gets a new object on each boxing, so == on two Double variables is almost never true.
Changing the cache size
The lower bound of the Integer cache is fixed at -128. The upper bound is configurable. HotSpot reads the flag -XX:AutoBoxCacheMax=<n> when the cache is initialized, and the cache then covers -128 to n. For example, java -XX:AutoBoxCacheMax=2000 CacheSurprise makes c == d print true, because 128 is now inside the cache.
The constructors always allocate
The cache is a property of valueOf, not of the class. The constructors new Integer(int) and new Integer(String) never consult it. Each call returns a fresh object:
public class ConstructorVersusValueOf {
@SuppressWarnings("removal")
public static void main(String[] args) {
Integer x = new Integer(5);
Integer y = new Integer(5);
System.out.println(x == y); // false
System.out.println(Integer.valueOf(5) == Integer.valueOf(5)); // true
}
}The wrapper constructors have been deprecated since Java 9 and are marked for removal. Calling them compiles with a warning, which @SuppressWarnings("removal") hides here only so the example stays clean. Use valueOf or autoboxing in real code. The next chapters in this series cover valueOf and the other conversion methods in more detail.
Integer.valueOf(String) also goes through the cache. It parses the string to an int and then calls valueOf(int). By contrast, Integer.parseInt(String) returns a primitive, so no object is involved at all.
When == is safe and when it is not
The result of == depends on the types of its two operands, not only on the values.
- If both operands are wrapper references, the comparison is by identity. This is the case that produces the surprise.
- If one operand is a primitive, Java unboxes the wrapper and compares numerically. This comparison is always by value.
- If the operands are two different wrapper types, such as
IntegerandLong, the code does not compile. The compiler reports "incomparable types".
This program shows the three cases, plus two related traps with equals:
public class MixedComparison {
public static void main(String[] args) {
Integer boxed = 1000;
int primitive = 1000;
Integer other = 1000;
System.out.println(boxed == primitive); // true: boxed is unboxed first
System.out.println(boxed == other); // false: two objects, compared by identity
System.out.println(boxed.equals(other)); // true: compares the values
Long big = 1000L;
System.out.println(big == primitive); // true: big is unboxed, the int widens to long
System.out.println(big.equals(1000)); // false: 1000 boxes to Integer, not Long
System.out.println(big.equals(1000L)); // true: same type and same value
// System.out.println(boxed == big); // compile error: incomparable types
}
}The big.equals(1000) line is a common bug. The equals method of every wrapper class first checks that the argument is the same wrapper type. An Integer is never equal to a Long, even when the numbers match.
A realistic bug
The comparison problem rarely appears in a tiny demo like the ones above. It appears in ordinary code that reads values out of collections. This method counts how many neighbors in a list are equal:
import java.util.List;
public class AdjacentDuplicates {
static int countBuggy(List<Integer> values) {
int count = 0;
for (int i = 1; i < values.size(); i++) {
if (values.get(i) == values.get(i - 1)) { // compares references
count++;
}
}
return count;
}
static int countFixed(List<Integer> values) {
int count = 0;
for (int i = 1; i < values.size(); i++) {
if (values.get(i).equals(values.get(i - 1))) { // compares values
count++;
}
}
return count;
}
public static void main(String[] args) {
List<Integer> small = List.of(5, 5, 5);
List<Integer> large = List.of(500, 500, 500);
System.out.println(countBuggy(small)); // 2
System.out.println(countBuggy(large)); // 0 on a default JVM
System.out.println(countFixed(small)); // 2
System.out.println(countFixed(large)); // 2
}
}The buggy version passes any test that uses small numbers such as ages, counts, or indexes. It fails in production when the data contains larger values such as IDs or timestamps. The cause is the cache boundary at 127, which has nothing to do with your program's logic. This is why tests with small sample values can hide the bug.
Rules for comparing wrappers
- Compare two wrapper references with
equals, or withcompareTo(...) == 0. Both compare values. - If either side may be
null, useObjects.equals(a, b). It returnstruewhen both arenulland never throws. - If you need a numeric comparison and both values are known to be non-null, unbox one side explicitly:
a.intValue() == b. - Use
Integer.compare(a, b)when ordering, for example inside a comparator. Do not subtract the values, because subtraction can overflow. - Do not use
==to test wrappers, even for small values. A comparison that works only because of the cache is a bug waiting for a different input.
Why the cache exists
The cache is an optimization for memory and speed. Small numbers are by far the most common values in programs, such as loop counters, list sizes, enum ordinals, and flags. Sharing one object per small value avoids allocating millions of short-lived objects. Sharing is safe because wrapper objects are immutable. No code can change the value inside a shared Integer, so one object can serve every user.
Immutability is also why identity almost never matters for wrappers. The language gives you equals for value comparison, and the cache turns the leftover identity comparison into an unreliable result rather than an error.
Edge cases to remember
- Synchronizing on a boxed value, such as
synchronized (counter)wherecounteris anInteger, is a serious bug. Small values are shared across the whole JVM, so unrelated code can end up using the same lock. Use a dedicated lock object instead. - A
static final Integerconstant holding a small number is the same object as every other boxed copy of that number. This does not change anything about how you should compare them. Integer a = 1000; a++;creates a newIntegereach time, because the object cannot change. The expressiona++compiles to unboxing, adding one, and callingvalueOfagain. Any other variable that pointed at the old object is unaffected.new Integer(5) == Integer.valueOf(5)is alwaysfalse, because the constructor bypasses the cache.- Results with
FloatandDoubledo not depend on a cache range, so==on two boxed floating-point values is almost alwaysfalse, whatever the value.
Summary
Autoboxing calls valueOf, and valueOf returns shared objects for a small range of values, namely -128 to 127 for Integer, Short, and Long, 0 to 127 for Character, and both Boolean values. Outside that range, and for Float and Double at any value, each boxing creates a new object. Applying == to two wrapper references compares those objects' identities, so the result depends on the value. Compare wrappers with equals, compareTo, or Objects.equals, and reserve == for cases where at least one side is a primitive.
Exercise
Given Integer p = 200; Integer q = 200; int r = 200;, what do p == q, p == r, and p.equals(q) print on a default JVM, and why?
Show answer
p == q prints false, because 200 is outside the -128 to 127 cache range, so p and q are different objects and == compares references. p == r prints true, because one operand is a primitive, so p is unboxed and the comparison is numeric. p.equals(q) prints true, because equals compares the stored values.
Exercise
A method contains Long total = 50L; if (total.equals(50)) { ... }. Will the body run? Fix the condition without changing the type of total.
Show answer
The body will not run. The literal 50 is an int, so it boxes to Integer, and Long.equals returns false for any argument that is not a Long. Use total.equals(50L), which boxes to Long, or total == 50, which unboxes total and compares numerically.
Exercise
Why is Objects.equals(a, b) a better default than a.equals(b) when comparing two Integer values read from a Map?
Show answer
Map.get returns null for a missing key. Calling a.equals(b) on a null a throws a NullPointerException. Objects.equals(a, b) returns true if both are null, false if only one is null, and otherwise calls a.equals(b).