The Plain Picture#
Some shipping services only accept boxes — they won't take a loose apple. So you put the apple in a small box. The box costs extra space and time to pack and unpack, and an empty box (with no apple) is possible too.
The Real Names#
Each primitive type has a wrapper class that holds one value as an object:
| Primitive | Wrapper |
|---|---|
int | Integer |
long | Long |
double | Double |
boolean | Boolean |
char | Character |
byte, short, float | Byte, Short, Float |
Why wrappers exist: Java's collections (
ArrayList,HashMap— Collections, From the Inside) and generics (Exceptions and Generics) can only hold objects, not primitives.List<int>is illegal;List<Integer>is fine.Autoboxing — Java automatically wraps a primitive when an object is needed (
Integer x = 5;). Unboxing — it automatically unwraps when a primitive is needed (int y = x;).
Under the Hood#
The Integer cache trap#
Integer x1 = 127,
y1 = 127,
x2 = 128,
y2 = 128;
System.out.println((x1 == y1) + " " + (x2 == y2) + " " + x2.equals(y2));
// true false trueAutoboxing calls Integer.valueOf, which keeps a cache of Integer objects for −128 to 127. So boxing 127 twice gives the same
cached object (== true), but 128 creates two separate objects (== false). It's the String pool story again (Ch 6): == compares
references.
In DSA this bites when comparing values from collections: map.get(a) == map.get(b) works in small tests (small numbers) and fails on
large ones. Compare wrapper objects with .equals, or unbox to primitives first (int v = map.get(a);).
Unboxing null → NullPointerException#
A wrapper can be null (the empty box). Unboxing null throws:
Integer maybe = null;
int v = maybe; // NullPointerException when unboxing nullClassic cause: int count = map.get(key); when the key isn't in the map (get returns null). Use map.getOrDefault(key, 0)
(Collections, From the Inside).
The cost of boxing — measured#
One million numbers stored two ways, measured on this Mac:
int[]: 3 MB
ArrayList<Integer>: 21 MBEach boxed Integer is a separate heap object with a header (about 16 bytes), plus a 4–8 byte reference to it in the list — versus 4
bytes per int in an array, packed side by side for the cache (How Computers Work Ch 6). For large numeric data in DSA, prefer
primitive arrays.
Character helpers — used constantly in string problems#
Character.isDigit('7') // true
Character.isLetter('a') // true
Character.isLetterOrDigit('_') // false ← "alphanumeric" checks, e.g. valid palindrome problems
Character.toLowerCase('Q') // 'q'
Character.getNumericValue('7') // 7
'7' - '0' // 7 ← the usual quick way (01_java_basics.md Ch 3)And the parsing helpers from Java Basics Ch 4 are static methods on wrappers: Integer.parseInt, Long.parseLong,
Integer.MAX_VALUE, Integer.toBinaryString(5) → "101".
Gotchas
==onInteger,Longetc. — same trap as strings. Use.equalsor unbox.Long l = 5;doesn't compile (5 is anint, which can't be boxed toLong); write5L.list.remove(1)on aList<Integer>removes the element at index 1, not the value 1 — uselist.remove(Integer.valueOf(1))for the value. (Overloading, Java Basics Ch 7, picksremove(int index)because an exactintmatch beats boxing.)
Check yourself
5 questionsWhy do wrapper classes exist?
Show answerHide answer
Collections and generics can only hold objects, so primitives need object versions.
What are autoboxing and unboxing?
Show answerHide answer
Automatic conversion from primitive to wrapper object and back.
Why is Integer a = 1000, b = 1000; a == b false, but true for 100?
Show answerHide answer
Integer.valueOf caches −128..127, so 100 gives the same cached object; 1000 gives two separate objects, and == compares references.
What happens with int c = map.get("missing");?
Show answerHide answer
get returns null, and unboxing null into int throws a NullPointerException.
Why is int[] better than ArrayList<Integer> for a million numbers?
Show answerHide answer
Far less memory (4 bytes per element vs a whole object plus a reference) and better cache behaviour.