Autoboxing and Unboxing

Collections and generics can only hold objects, so Java wraps primitive values in objects such as Integer and unwraps them again, automatically, since Java 5. The conversion is invisible in the source code, which is exactly why it causes bugs: == that works for 127 but not 128, NullPointerExceptions on lines with no visible object, and loops that run several times slower. This page shows what the compiler really generates and each trap that follows from it.

Contents

Primitives, wrapper classes and why boxing exists

Java's eight primitive types (int, double and so on) are plain values, not objects. Generic code, such as List<T> or Map<K, V>, works only with objects. So each primitive type has a wrapper class, an immutable object that holds one value. Converting a primitive to its wrapper is boxing, and the reverse is unboxing. Since Java 5 the compiler does both automatically wherever the types require it, which is called autoboxing.

Wrapper classes and their caches
PrimitiveWrapperValues cached by valueOf
booleanBooleanBoth (TRUE, FALSE)
byteByteAll 256
shortShort-128 to 127
intInteger-128 to 127 (upper bound configurable)
longLong-128 to 127
charCharacter0 to 127
floatFloatNone
doubleDoubleNone

A wrapper object costs memory: an Integer is 16 bytes plus a 4-byte reference to it, against 4 bytes for an int (measured on the arrays page). Wrappers can also be null, which primitives cannot. Both facts are behind the traps below.

What the compiler generates

Autoboxing is a compile-time feature: the JVM knows nothing about it. To see this, the program compiles a three-line method with javac and disassembles it with javap, both run from inside Java through java.util.spi.ToolProvider. It keeps only the lines that call methods, cast or add.

Java
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.spi.ToolProvider;

// Compiles a tiny class and disassembles it with javap to show the hidden calls
public class WhatCompilerGenerates {

    static final String SOURCE = """
            import java.util.List;
            import java.util.ArrayList;

            class Boxing {
                int run() {
                    List<Integer> list = new ArrayList<>();
                    list.add(42);            // int -> Integer
                    int x = list.get(0);     // Integer -> int
                    return x + 1;
                }
            }
            """;

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("boxing");
        Files.writeString(dir.resolve("Boxing.java"), SOURCE);
        run("javac", "-d", dir.toString(), dir.resolve("Boxing.java").toString());
        String code = run("javap", "-c", "-cp", dir.toString(), "Boxing");
        code.lines()
                .filter(l -> l.matches(".*(invoke|checkcast|iadd).*"))
                .map(l -> l.replaceAll("\\s+//", "   //").strip())
                .forEach(System.out::println);
    }

    static String run(String tool, String... args) {
        StringWriter out = new StringWriter();
        PrintWriter pw = new PrintWriter(out);
        ToolProvider.findFirst(tool).orElseThrow().run(pw, pw, args);
        pw.flush();
        return out.toString();
    }
}

Output:

Output
1: invokespecial #1   // Method java/lang/Object."<init>":()V
4: invokespecial #9   // Method java/util/ArrayList."<init>":()V
11: invokestatic  #10   // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
14: invokeinterface #16,  2   // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
22: invokeinterface #22,  2   // InterfaceMethod java/util/List.get:(I)Ljava/lang/Object;
27: checkcast     #11   // class java/lang/Integer
30: invokevirtual #26   // Method java/lang/Integer.intValue:()I
36: iadd
  • list.add(42) became Integer.valueOf(42) followed by List.add(Object). Boxing always uses valueOf, which is where the cache comes in.
  • int x = list.get(0) became List.get, a checkcast to Integer (because of generic type erasure), and then intValue(). That intValue() call is the hidden method call that throws NullPointerException when the value is null.
  • The addition x + 1 is a plain iadd on primitives: arithmetic always happens on unboxed values.

Boxing in practice, and == on wrappers

The program boxes and unboxes through a list and arithmetic, then compares Integer objects with == for 127 and 128, the two values on either side of the cache limit.

Java
import java.util.ArrayList;
import java.util.List;

public class BoxingBasics {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(5);                       // autoboxing: Integer.valueOf(5)
        int first = list.get(0);           // unboxing: list.get(0).intValue()
        System.out.println("first = " + first);

        Integer boxed = 10;
        int doubled = boxed * 2;           // unboxed for arithmetic
        System.out.println("doubled = " + doubled);

        // The Integer cache: valueOf returns shared objects for -128..127
        Integer a = 127;
        Integer b = 127;
        Integer c = 128;
        Integer d = 128;
        System.out.println("127 == 127: " + (a == b));
        System.out.println("128 == 128: " + (c == d));
        System.out.println("128 equals 128: " + c.equals(d));

        // Mixed comparison: == between Integer and int unboxes, so it compares values
        int plain = 128;
        System.out.println("Integer 128 == int 128: " + (c == plain));
    }
}

Output:

Output
first = 5
doubled = 20
127 == 127: true
128 == 128: false
128 equals 128: true
Integer 128 == int 128: true
  • Boxing and unboxing happen without any code: list.add(5), int first = list.get(0) and boxed * 2 all compile and work.
  • == on two Integer objects compares references, not values. For 127 both variables got the same cached object from valueOf, so it printed true; 128 is outside the cache, so two separate objects were created and it printed false. Code that compares IDs with == passes every test with small numbers and fails in production with large ones.
  • equals compares values and is correct for any number.
  • Integer == int unboxes the Integer and compares numbers, so it printed true. The rule: if either side of == is a primitive, it is a numeric comparison; if both are wrappers, it is an identity comparison.

The caches in detail

Every wrapper's valueOf may return a shared object, and some must. The program checks the boundaries for each type with autoboxing, which uses valueOf, and then a second program raises the Integer cache limit with a JVM option.

Java
public class CacheRanges {

    public static void main(String[] args) {
        // valueOf (and therefore autoboxing) reuses objects for small values
        Integer a = 127;
        Integer b = 127;
        System.out.println("Integer   127 same object: " + (a == b));
        Integer c = 128;
        Integer d = 128;
        System.out.println("Integer   128 same object: " + (c == d));
        Integer e = -128;
        Integer f = -128;
        System.out.println("Integer  -128 same object: " + (e == f));
        Long g = 127L;
        Long h = 127L;
        System.out.println("Long      127 same object: " + (g == h));
        System.out.println("Character 127 same object: "
                + (Character.valueOf((char) 127) == Character.valueOf((char) 127)));
        System.out.println("Character 128 same object: "
                + (Character.valueOf((char) 128) == Character.valueOf((char) 128)));
        System.out.println("Boolean  true same object: " + (Boolean.valueOf(true) == Boolean.TRUE));
        Double x = 1.0;
        Double y = 1.0;
        System.out.println("Double    1.0 same object: " + (x == y));
    }
}

Output:

Output
Integer   127 same object: true
Integer   128 same object: false
Integer  -128 same object: true
Long      127 same object: true
Character 127 same object: true
Character 128 same object: false
Boolean  true same object: true
Double    1.0 same object: false
  • The Java Language Specification (section 5.1.7) requires that boxing a constant of type int, short, byte or long from -128 to 127 always gives the same object, and the same for char values up to 127 and for true and false; valueOf uses the same cache for computed values. The output matches: -128 and 127 were shared, 128 was not.
  • Double and Float have no cache, so even 1.0 gave two different objects.
Java
public class CacheMax {

    public static void main(String[] args) {
        // Run with -XX:AutoBoxCacheMax=1000 to cache Integer values up to 1000
        Integer a = 128;
        Integer b = 128;
        Integer c = 1000;
        Integer d = 1000;
        Integer e = 1001;
        Integer f = 1001;
        System.out.println("128 same object:  " + (a == b));
        System.out.println("1000 same object: " + (c == d));
        System.out.println("1001 same object: " + (e == f));
    }
}

Output, run with java -XX:AutoBoxCacheMax=1000 CacheMax:

Output
128 same object:  true
1000 same object: true
1001 same object: false

With the option, Integer values up to 1,000 are cached, and only 1,001 got separate objects. The option exists for performance tuning in programs that box many medium-sized numbers. It does not make == on wrappers a good idea: the code would still break on a JVM started without it.

The constructors such as new Integer(5) always create a new object and bypass the cache. They have been deprecated since Java 9 and marked for removal since Java 16 (JEP 390), as part of making wrappers value-based classes; javac also warns when code uses synchronized on a wrapper object, because cached instances are shared across the whole JVM.

Traps: null, overloading and equals across types

Each trap in this program comes from a conversion the source code does not show. They were chosen because each one has caused real production bugs.

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BoxingTraps {

    static String which(long value) {
        return "which(long)";
    }

    static String which(Integer value) {
        return "which(Integer)";
    }

    public static void main(String[] args) {
        // 1. Unboxing null throws
        Map<String, Integer> stock = new HashMap<>();
        try {
            int apples = stock.get("apple");
            System.out.println(apples);
        } catch (NullPointerException e) {
            System.out.println("unboxing a missing map value: NullPointerException");
        }
        System.out.println("safer: " + stock.getOrDefault("apple", 0));

        // 2. remove(int) vs remove(Object)
        List<Integer> nums = new ArrayList<>(List.of(10, 20, 30));
        nums.remove(1);                          // index 1
        System.out.println("remove(1):                   " + nums);
        nums.remove(Integer.valueOf(10));        // the value 10
        System.out.println("remove(Integer.valueOf(10)): " + nums);

        // 3. A ternary mixing int and Integer unboxes the Integer
        Integer maybe = null;
        boolean useDefault = false;
        try {
            Integer result = useDefault ? 0 : maybe;
            System.out.println(result);
        } catch (NullPointerException e) {
            System.out.println("ternary with int and null Integer: NullPointerException");
        }

        // 4. equals across types is false even for the same number
        Long big = 1L;
        Integer small = 1;
        System.out.println("Long 1 equals Integer 1: " + big.equals(small));
        System.out.println("Long 1 == 1L after unboxing: " + (big == 1L));

        // 5. Overload resolution prefers widening (int -> long) over boxing (int -> Integer)
        System.out.println("which(5) calls " + which(5));
    }
}

Output:

Output
unboxing a missing map value: NullPointerException
safer: 0
remove(1):                   [10, 30]
remove(Integer.valueOf(10)): [30]
ternary with int and null Integer: NullPointerException
Long 1 equals Integer 1: false
Long 1 == 1L after unboxing: true
which(5) calls which(long)
  1. Unboxing null: stock.get("apple") returned null because the key is missing, and assigning it to an int called intValue() on null. The line contains no visible method call, which makes the stack trace confusing. Use getOrDefault, or keep the value as Integer and check for null.
  2. remove(int) or remove(Object): List<Integer> has both. nums.remove(1) chose remove(int index) and removed 20, the element at index 1, not the value 1. To remove a value, pass an Integer: remove(Integer.valueOf(10)).
  3. The ternary operator: useDefault ? 0 : maybe has an int on one side and an Integer on the other, so the rules make the whole expression an int, and maybe is unboxed even though the result is assigned to an Integer. With maybe being null, that throws. Writing Integer.valueOf(0) makes both sides Integer and avoids it.
  4. equals across types: Long.equals(Integer) is false even for the same number, because equals first checks the class. This bites when a Map<Long, ...> is queried with an int key: map.get(5) boxes to Integer and never matches. Comparing big == 1L unboxes and works.
  5. Overloading: given which(long) and which(Integer), the call which(5) chose which(long). Java first looks for a method reachable by widening only, and considers boxing only if none exists. This rule, from Java 5, kept old code that relied on widening working unchanged.

The cost of boxing

Each box is an object allocation, and each unbox is a memory read through a reference. The program sums 50 million numbers with a long and with a Long accumulator, then sums 5 million numbers stored as List<Integer> and as int[]. Each timing is the best of 3 runs; this is a rough comparison, not a benchmark (see the JMH page).

Java
import java.util.List;
import java.util.stream.IntStream;

public class BoxingCost {

    static long sumBoxed(int n) {
        Long total = 0L;                   // boxed accumulator: a new Long on most additions
        for (int i = 0; i < n; i++) {
            total += i;
        }
        return total;
    }

    static long sumPrimitive(int n) {
        long total = 0L;
        for (int i = 0; i < n; i++) {
            total += i;
        }
        return total;
    }

    interface Job {
        long run();
    }

    // Best of 3 runs, so JIT compilation is not part of the measurement
    static void time(String name, Job job) {
        long best = Long.MAX_VALUE;
        long result = 0;
        for (int run = 0; run < 3; run++) {
            long t = System.nanoTime();
            result = job.run();
            best = Math.min(best, System.nanoTime() - t);
        }
        System.out.printf("%-34s %,d ms  (sum %d)%n", name, best / 1000000, result);
    }

    public static void main(String[] args) {
        int n = 50000000;
        time("long accumulator", () -> sumPrimitive(n));
        time("Long accumulator", () -> sumBoxed(n));

        List<Integer> boxedList = IntStream.range(0, 5000000).boxed().toList();
        int[] primitives = IntStream.range(0, 5000000).toArray();
        time("Stream<Integer> of 5M, mapToLong", () ->
                boxedList.stream().mapToLong(Integer::longValue).sum());
        time("IntStream over int[5M]", () -> IntStream.of(primitives).asLongStream().sum());
    }
}

Output (2-CPU Linux machine, JDK 21; times will differ on yours):

Output
long accumulator                   13 ms  (sum 1249999975000000)
Long accumulator                   80 ms  (sum 1249999975000000)
Stream<Integer> of 5M, mapToLong   10 ms  (sum 12499997500000)
IntStream over int[5M]             1 ms  (sum 12499997500000)
  • With a Long accumulator, total += i means unbox, add, and box a new Long, because values above 127 are not cached. Changing one letter, Long to long, made the loop several times faster and created no garbage.
  • Summing the boxed list read every Integer through a reference; the int[] version read contiguous memory and was much faster again. Primitive streams (IntStream, LongStream, DoubleStream) and methods such as mapToInt exist to avoid boxing in stream pipelines.
  • The JIT compiler can sometimes remove boxing through escape analysis, but it cannot be relied on, especially when boxed values are stored in collections.

Rules of thumb

Using wrappers safely
SituationDo
Comparing two wrapper valuesa.equals(b), Objects.equals(a, b) or Integer.compare, never ==
Reading from a map of numbersgetOrDefault, or check for null before unboxing
Local variables, counters, accumulatorsPrimitive types
Large amounts of numeric dataPrimitive arrays or primitive streams
A value that may be absentA wrapper (can be null) or OptionalInt
Map keys of type LongQuery with long values (5L), not int
Removing a number from a List<Integer>remove(Integer.valueOf(x))
Creating wrappersAutoboxing or valueOf; never the deprecated constructors

Related pages: data types, equals and hashCode, and generics, which is why boxing is needed at all.