Autoboxing Java Primitives vs Wrapper Types Pitfalls
Understand autoboxing in Java: primitives versus wrappers, the Integer cache, NullPointerException on unboxing, equality traps and memory cost.

Java has primitive types (int, double, boolean) and a wrapper class for each (Integer, Double, Boolean). Generics and collections work only with objects, so the compiler converts between the two. The conversion is convenient and has costs that show up at runtime. The types themselves are introduced in variables and data types.
What the compiler does
Integer boxed = 42; // Integer.valueOf(42)
int primitive = boxed; // boxed.intValue()
List<Integer> numbers = new ArrayList<>();
numbers.add(7); // numbers.add(Integer.valueOf(7))
int first = numbers.get(0); // numbers.get(0).intValue()Boxing wraps a primitive in an object, and unboxing extracts it. Both happen silently, which is the source of the trouble.
Trap 1: unboxing null
Integer count = map.get("missing"); // null
int total = count + 1; // NullPointerExceptionA wrapper can be null, and a primitive cannot. The arithmetic unboxes count, and the unboxing calls a method on null. This is the quiet source of many NullPointerExceptions, especially with Map.get, database columns mapped to Integer and optional JSON numbers. Guard it: map.getOrDefault("missing", 0), or use Optional, or keep a primitive field when the value is always present.
Trap 2: == on wrappers
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b); // true
System.out.println(c == d); // false
System.out.println(c.equals(d)); // trueInteger.valueOf returns cached objects for -128 to 127, so two boxes of 127 are the same object. Beyond that range each call creates a new object, and == compares references. The same cache exists for Long, Short, Byte and Character (0 to 127). Comparing wrappers with == therefore works in tests with small numbers and fails in production with large ones. Use equals, or Objects.equals when either side may be null, or unbox first.
Trap 3: overloads and the ternary
list.remove(1); // remove(int index)
list.remove(Integer.valueOf(1)); // remove(Object o)For a List<Integer>, the two remove overloads do different things, and the compiler picks the exact primitive match first. The ternary operator unboxes in surprising ways:
Integer value = flag ? 1 : null; // NullPointerException when flag is falseWhen one branch is int and the other null, the type of the expression becomes int, so the null is unboxed. Make both branches Integer: flag ? Integer.valueOf(1) : null.
Cost in memory and time
Each Integer is an object with a header (16 bytes on typical settings) and a pointer from the collection (4 or 8 bytes). A million Integers in an ArrayList take about 20 MB, and an int[] of a million takes 4 MB, as measured in object layout and footprint. Boxing in a hot loop creates garbage:
long sum = 0L; // primitive: fast
Long boxedSum = 0L; // boxed: allocates on every iteration beyond the cache
for (int i = 0; i < 1_000_000; i++) boxedSum += i;The second loop allocates around a million Long objects. The JIT can sometimes remove the allocation through escape analysis, see JIT compilation, but do not rely on it for hot paths.
What to do
- Use primitives for fields, locals and parameters that are always present.
- Use wrappers when absence matters (nullable column, optional field), and handle
nullon purpose. - Prefer primitive streams (
IntStream,mapToInt) and primitive specialisations for numeric work instead ofStream<Integer>. - Use
equalsfor wrapper comparisons. - For large numeric collections, consider arrays or primitive collection libraries.
The cache boundary, run on your machine
Integer.valueOf caches the values from -128 to 127, so two boxed values in that range are the same object and two outside it are not. This program shows the effect:
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b); // true
System.out.println(c == d); // false
System.out.println(c.equals(d)); // trueThe first comparison is true by accident of the cache, and the second is false because each 128 was boxed into a new object. Code that compares wrappers with == passes tests that use small numbers and fails in production when an id reaches 128. Use equals, or unbox one side by comparing c.intValue() == d.intValue(). A static analysis rule flags the comparison, and enabling it removes the class of bug.
Overloads that pick the wrong method
When a method is overloaded on a primitive and an object, the choice depends on the exact types, and boxing is the last resort. List.remove has two forms:
List<Integer> list = new ArrayList<>(List.of(10, 20, 30, 1));
list.remove(1); // removes the element at index 1, so 20 goes
list.remove(Integer.valueOf(1)); // removes the element equal to 1The first call picks remove(int index), because an int argument matches without boxing. People who wanted to remove the value 1 lose the element at position 1 instead, with no error. The same list code behaves correctly with a List<String>, which is why the bug stays hidden until someone uses numbers.
Different wrappers are never equal
equals on a wrapper first checks the class. An Integer and a Long with the same numeric value are not equal:
Long id = 5L;
System.out.println(id.equals(5)); // false: 5 is boxed to Integer
System.out.println(id.equals(5L)); // trueThe first line compiles and is false. It appears in code that compares a Long id from a database with an int literal, and in Map<Long, ...> lookups with an Integer key, where map.get(5) always returns null. Use a literal of the right type, or compare values with longValue().
What boxing costs in a loop
A boxed accumulator creates garbage on each update:
Long sum = 0L;
for (int i = 0; i < 100_000_000; i++) {
sum += i; // unbox, add, box a new Long
}Declaring long sum instead removes 100 million allocations, and on a typical laptop the primitive version runs several times faster. Beyond the loop, a List<Integer> of a million elements takes about 16 MB for the references and 16 MB for the objects, against 4 MB for an int[]. For numeric work, use primitive arrays or IntStream, and keep boxed types for places where an object is required, such as collection elements and nullable fields.
A short guide to choosing
| Situation | Use |
|---|---|
| Local variable, loop counter, accumulator | Primitive |
| Field that can be absent | Wrapper, or OptionalInt as a return type |
| Collection element | Wrapper, no alternative in the standard library |
| Large numeric data | Primitive array or a primitive stream |
| Comparing wrappers | equals, or unbox explicitly |
| A database column that allows NULL | Wrapper, and read it with getObject(col, Integer.class) |
The pattern is that a primitive says "always has a value", and a wrapper says "may be missing". Choosing by that meaning removes most surprises, since it makes the null case part of the type.
Letting the tools find these for you
Most of the traps in this post can be found by static analysis, and enabling the checks costs little. IntelliJ highlights unboxing of possibly null values and boxed comparisons with ==. SpotBugs reports comparisons of boxed values and inefficient use of the Integer constructor. Error Prone has checks for the List.remove ambiguity and for equals between different wrapper types. Turn them on as warnings first, fix the existing ones in a single pass, and then make them errors for new code.
A project that does this removes a whole class of bug reports, and the reviewers stop spending attention on a pattern that a tool catches better.
Where this does not apply
The cost is irrelevant in code that runs a few times. Project Valhalla aims to reduce the gap between objects and primitives in future Java releases. The conversion rules are defined in JLS section 5.1.7 and 5.1.8, and the Java tutorial on autoboxing is a gentler read.


