Autoboxing
Autoboxing is the compiler automatically converting a primitive such as int into its wrapper object Integer, and unboxing is the reverse. It hides a real allocation behind ordinary-looking code.
Detailed Explanation
Java's generics only work with reference types. You cannot write List<int>. Every primitive therefore has a matching wrapper class: Integer, Long, Double, Boolean, Character, and so on. Before Java 5 you converted by hand, writing list.add(new Integer(count)) and int n = ((Integer) list.get(0)).intValue(). It was noisy and everybody did it.
Java 5 added autoboxing so the compiler inserts those conversions for you. Writing List<Integer> ids = new ArrayList<>(); ids.add(42); compiles to a call to Integer.valueOf(42). Reading int first = ids.get(0); compiles to intValue(). The syntax got clean. The costs did not go away, they became invisible, and that is the entire reason this term needs explaining.
Three costs follow. The first is allocation: each boxed value is a heap object with a header, so a million boxed integers cost roughly four times a int[] of the same length and add garbage collection pressure. The second is indirection: List<Integer> stores pointers, so summing it chases memory all over the heap instead of walking a contiguous array. The third is null: a wrapper can be null, and unboxing null throws NullPointerException at a line that contains no visible method call.
The conversion is not free of surprises either. Integer.valueOf maintains a cache for values from −128 to 127, so two boxed Integer objects holding 100 are the same instance and == returns true, while two holding 1000 are different instances and == returns false. The cache exists because small integers dominate real programs. The consequence is a bug that passes every small test and fails on production data.
Autoboxing also interacts badly with overload resolution. Given remove(int index) and remove(Object o) on List, calling list.remove(1) picks the index overload, while list.remove(Integer.valueOf(1)) picks the object overload. One deletes position 1, the other deletes the value 1. Nothing in the call site tells you which.
You reach for wrappers when you genuinely need an object: elements in a collection, type arguments to generics, a value that can be absent, a field mapped from a nullable database column. You avoid them in numeric loops, in large arrays, and on hot paths.
Java gives you tools to stay unboxed. IntStream, LongStream, and DoubleStream exist so that stream.mapToInt(Order::quantity).sum() never allocates a box. Primitive arrays stay primitive. Libraries such as Eclipse Collections and fastutil provide IntArrayList and primitive-keyed maps for cases where the JDK forces boxing on you.
Project Valhalla aims to remove this whole distinction eventually with value classes. Until it ships, boxing remains something you should be able to see in your head while reading code.
Code Examples
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class BoxingBasics {
public static void main(String[] args) {
List<Integer> scores = new ArrayList<>();
scores.add(95); // autoboxed: Integer.valueOf(95)
int best = scores.get(0); // unboxed: intValue()
System.out.println(best); // prints: 95
// The Integer cache covers -128..127 only.
Integer smallA = 127, smallB = 127;
Integer bigA = 128, bigB = 128;
System.out.println(smallA == smallB); // prints: true — same cached object
System.out.println(bigA == bigB); // prints: false — two objects
System.out.println(bigA.equals(bigB));// prints: true — always use equals
// Unboxing a missing map value throws, and the line looks harmless.
Map<String, Integer> visits = Map.of("ada", 3);
Integer boxed = visits.get("grace"); // null, no exception yet
// int count = boxed; // would throw NullPointerException here
int count = boxed == null ? 0 : boxed;
System.out.println(count); // prints: 0
}
}import java.util.List;
import java.util.stream.IntStream;
public class AvoidingBoxing {
record Order(String sku, int quantity) { }
public static void main(String[] args) {
List<Order> orders = List.of(new Order("kb-1", 2), new Order("ms-2", 5));
// mapToInt produces an IntStream: the sum never allocates an Integer.
int totalUnits = orders.stream().mapToInt(Order::quantity).sum();
System.out.println(totalUnits); // prints: 7
// Contrast: this boxes every element, then unboxes to add.
int boxedTotal = orders.stream().map(Order::quantity).reduce(0, Integer::sum);
System.out.println(boxedTotal); // prints: 7, with extra allocations
// Primitive range, no boxing at all.
System.out.println(IntStream.rangeClosed(1, 5).sum()); // prints: 15
}
}Common Gotchas
Unboxing `null` throws with no visible call
`int total = map.get(key);` throws `NullPointerException` when the key is absent. Use `getOrDefault`, or keep the value as `Integer` and check it.
`==` on wrappers is only right by accident
it compares identity, and the −128 to 127 cache makes it behave correctly for small values. Compare with `equals` or unbox one side explicitly.
Boxing in a loop is a real allocation cost
a `Long` accumulator inside a tight loop allocates a new object per iteration. Declare the accumulator as `long` and let the box happen once at the end, if at all.
Overload resolution prefers the unboxed match
`List.remove(1)` removes index 1, not the value 1. Cast to `Integer` when you mean the value, and read this carefully in code reviews.