Skip to content
Codescope

Autoboxing & the Integer cache

int is a value. Integer is an object. Java hides the conversion, and that is exactly the problem.

core9 min7 steps

Before you start

**Autoboxing** is Java's convenience feature that quietly converts primitives into their wrapper objects (and back). When you write Integer x = 5, the compiler inserts a call to Integer.valueOf(5) for you.

It's supposed to be invisible — but it's not, in two famous ways. First, == on wrapper objects compares references, not values. Second, unboxing a null Integer throws NullPointerException.

This lesson visualises what autoboxing actually does, and then walks the notorious case where Integer x = 127; Integer y = 127; x == y is true but the same code with 128 is false.

Stack

main()
pint
127

Generics cannot hold primitives, which is why List<Integer> exists at all.

Step 1 of 7. int and Integer are not the same thing. `int p = 127` stores the number directly in the variable's slot — 4 bytes, no object. `Integer` is a class. A variable of that type holds a *reference* to an object on the heap that wraps the number, costing an object header plus the value.

01 / 07

Step 01 / 07

int and Integer are not the same thing

int p = 127 stores the number directly in the variable's slot — 4 bytes, no object.

Integer is a class. A variable of that type holds a *reference* to an object on the heap that wraps the number, costing an object header plus the value.

autoboxing.javaJava
import java.util.ArrayList;import java.util.List;public class Main {    public static void main(String[] args) {        int     p = 127;        Integer a = 127;      // autoboxed from the cache        Integer b = 127;      // same cached object        System.out.println(a == b);    // true        Integer c = 128;      // outside the cache        Integer d = 128;      // a second object        System.out.println(c == d);    // false!        System.out.println(c.equals(d)); // true        List<Integer> nums = new ArrayList<>();        for (int i = 0; i < 3; i++) nums.add(i);  // boxes every time        Integer maybe = null;        int oops = maybe;     // NullPointerException on unboxing    }}