Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 13 / Topic 4 of 8

Autoboxing cost

Autoboxing is the compiler silently wrapping a primitive in its object wrapper (int → Integer) wherever an object is required — a generic collection like List<Integer>, for instance, which cannot hold a primitive int directly. Each box is a real heap allocation; unboxing back to int for arithmetic is a real method call. A primitive loop does neither. Think of mailing a coin versus mailing a padded envelope with one coin inside: the coin itself is the same size either way, but every trip now needs an envelope made, addressed and later opened.

List<Integer> boxed = new ArrayList<>();
for (int i = 0; i < n; i++) {
    boxed.add(i);             // autoboxed: int -> Integer, one object per value
}
$ javac BoxingCost.java
$ java BoxingCost
== 1. Measured cost: a primitive int loop vs. a List<Integer> of the same numbers ==
primitive loop: 2 ms total (20 repeats, n=500,000)
boxed loop:     49 ms total
boxed was about 19.7x slower here
(varies by machine and run — the ratio is what matters)
The gap is every int getting wrapped in a new Integer object, then unwrapped again, instead of staying a plain number on the stack.

== 2. The Integer cache: boxing small numbers reuses objects, boxing bigger ones does not ==
Integer 127 == 127 (boxed): true
Integer 128 == 128 (boxed): false
a127.equals(b127): true
a128.equals(b128): true
The cache range is an implementation detail (JDK default: -128 to 127).
The rule that never breaks: compare boxed numbers with .equals(), never ==.

Summing half a million numbers as a plain int loop versus building and summing a List<Integer> of the same values showed the boxed version taking roughly 20 times longer here — every value paid for an object allocation (and later, garbage collection) that the primitive loop never needed. The second block shows the JDK's small-integer cache, which quietly reuses Integer objects for values -128 to 127 (an implementation detail, not a language guarantee) — Integer 127 == 127 comes out true purely by luck of being in the cached range, while Integer 128 == 128 is false, two separate objects with equal value. This is precisely section 3's == trap wearing a number's clothing: the fix is identical — compare with .equals(), always, for any boxed type.

⚠️ Integer a = 127; Integer b = 127; a == b being true is not something to rely on. It's a cache implementation detail with an arbitrary cutoff. The same code with 200 instead of 127 silently becomes false.

Full program: examples/BoxingCost.java.

Done here? The practice set for Part 13 — including the solutions — is on the part page.

Search the guide