Wrapper Classes
& Autoboxing
Learn how Java bridges primitive types and objects with wrapper classes, and how autoboxing and unboxing make this seamless.
Why Do We Need Wrapper Classes?
Java has two type systems: primitives (like int, double, boolean) that hold raw values, and objects that live on the heap. Many Java features, like ArrayList, only work with objects: you can't write ArrayList<int>.
The Three Key Wrapper Classes
Primitive vs Object in Memory
A primitive stores its value directly on the stack. A wrapper object lives on the heap and contains the value inside, plus it inherits methods from Object.
What Is Autoboxing?
The literal 42 is a primitive int. Java automatically calls Integer.valueOf(42) behind the scenes to create the wrapper object.
What Is Unboxing?
When you assign a wrapper object to a primitive variable, Java calls .intValue(), .doubleValue(), or .booleanValue() automatically.
The Autoboxing and Unboxing Cycle
Primitives vs Wrappers: Key Differences
| Primitive | Wrapper | |
|---|---|---|
| Type | int, double, boolean | Integer, Double, Boolean |
| Default value | 0, 0.0, false | null |
| Memory | Stack (fast) | Heap (object overhead) |
| Can be null? | No | Yes |
| Use in ArrayList | No | Yes |
| Equality check | == compares values | == compares references |
How to Use Wrappers in Practice
Example 1: ArrayList with Autoboxing
Example 2: Boolean Autoboxing
Example 3: The == Trap with Integers
The Integer Cache Explained
Common Mistakes to Avoid
Summary: Wrapper Classes at a Glance
| Concept | What It Does | Example |
|---|---|---|
| Wrapper Class | Wraps primitive in an object | Integer, Double, Boolean |
| Autoboxing | Primitive → Object (auto) | Integer n = 5; |
| Unboxing | Object → Primitive (auto) | int x = obj; |
| .equals() | Compares wrapper values | a.equals(b) |
| Integer Cache | Reuses objects: -128 to 127 | == works only in this range |
Question 1 of 5
Which of the following correctly declares an ArrayList that can store integer values?
Question 2 of 5
What is the output of the following code?
Question 3 of 5
What happens when the following code runs?
Question 4 of 5
Which line demonstrates autoboxing?
Question 5 of 5
What is the correct way to compare two Double wrapper objects for value equality?