Wrapper Classes, Autoboxing and the Integer Cache

Difficulty: Beginner

Question

What are wrapper classes and autoboxing? Why does Integer a = 127, b = 127 give a == b true but 128 gives false?

Answer

Let me walk you through this one, because it produces some of the most surprising output in Java, and it catches out even people with two years of experience.

Java has eight primitive types (int, long, double, boolean and so on) that are fast and light, but they are not objects. Collections such as List and Map only store objects, and generics do not work with primitives. So Java provides a wrapper class for each: Integer for int, Long for long, Double for double, Boolean for boolean, Character for char, and so on. They also carry useful utilities like parseInt, compare and MAX_VALUE.

Autoboxing is the compiler automatically converting a primitive into its wrapper, and unboxing is the reverse. Writing Integer x = 5 really compiles to Integer.valueOf(5), and int y = x compiles to x.intValue(). This convenience is why you can write list.add(5) on a List of Integer.

Now the cache. The method Integer.valueOf does not always create a new object. To save memory and time, the Integer class keeps a cache of Integer objects for values from -128 to 127. If you autobox a value in this range, you get the same cached object every time. Outside the range, valueOf allocates a new object. Since == on objects compares references, 127 == 127 gives true (same cached object) while 128 == 128 gives false (two different objects). The upper bound of the cache can even be raised with the JVM flag -XX:AutoBoxCacheMax. Similar caches exist for Byte, Short, Long (-128 to 127), Character (0 to 127) and Boolean.

The lesson is simple: compare wrapper objects with equals, never with ==. And note that new Integer(5) always makes a new object, which is why those constructors are deprecated for removal since Java 9.

Here are the pitfalls I'd expect you to mention. First, NullPointerException on unboxing: Integer count = null; int c = count; throws an NPE because the compiler calls count.intValue(). This often bites when you read a possibly missing value from a Map, like int v = map.get(key). Second, mixed comparison: Integer x = 1000; int y = 1000; x == y is true, because one side is primitive, so the Integer is unboxed and compared numerically. Third, equals is type-strict: Long l = 127L; l.equals(127) is false because 127 is boxed as an Integer, and Long.equals requires another Long. Fourth, performance: autoboxing in loops, for instance using Long sum and doing sum += i, creates millions of temporary objects. Use the primitive type in hot paths. Fifth, ambiguous overloads: list.remove(int index) versus list.remove(Object o) behave differently when you pass an int or an Integer.

Finally, a design remark: prefer primitives for local calculations and wrappers only when you need nullability, collections or generics. In database entities, for example, an Integer field can represent a nullable column, while an int cannot.

Code examples

Integer cache and unboxing traps

import java.util.*;

public class BoxingDemo {
    public static void main(String[] args) {
        Integer a = 127, b = 127;
        Integer c = 128, d = 128;
        System.out.println(a == b);
        System.out.println(c == d);
        System.out.println(c.equals(d));

        Integer big = 1000;
        int prim = 1000;
        System.out.println(big == prim);

        Long l = 127L;
        System.out.println(l.equals(127));
        System.out.println(l.equals(127L));

        Map<String, Integer> map = new HashMap<>();
        try {
            int v = map.get("missing");
        } catch (NullPointerException e) {
            System.out.println("NPE on unboxing");
        }
    }
}

127 lies in the -128 to 127 cache, 128 does not. The mixed comparison unboxes the Integer. Long.equals rejects an Integer argument. map.get returns null and unboxing null throws.

Key points

Common follow-up questions

Interview tips

Concepts covered

Wrapper Classes, Autoboxing, Integer Cache, NullPointerException, equals

More Core Java & Collections questions