Wrapper
Classes
Learn how Java wraps primitives inside objects, enabling them to work with collections, generics, and the powerful features of the object-oriented world.
What Are Wrapper Classes?
Java has eight primitive types (like int, double, boolean) that store raw values directly in memory. But many parts of Java, such as ArrayLists and generics, require objects, not primitives.
Why Do Wrappers Exist?
Primitive → Object Mapping
Autoboxing & Unboxing
Java automatically converts between primitives and their wrapper objects. This two-way conversion is called autoboxing and unboxing.
int → Integer, automatically
Integer → int, automatically
How Autoboxing Works
Primitive vs Wrapper Object
| Primitive (int) | Wrapper (Integer) | |
|---|---|---|
| Stores | Raw value on stack | Object reference on heap |
| Default value | 0 | null |
| In ArrayList? | ✕ No | ✓ Yes |
| Equality check | == compares values | == compares references |
| Can be null? | ✕ No | ✓ Yes |
How to Use Wrapper Classes
Example: ArrayList with Integers
Example: Arithmetic with Wrappers
The == Trap with Wrappers
Key Methods to Know
Parsing Strings to Numbers
NullPointerException Risk
This commonly happens when an ArrayList<Integer> contains a null element and you try to assign it to a primitive int variable.
Common Mistakes
Summary Reference
| Concept | Details |
|---|---|
| AP Wrapper Types | Integer, Double |
| Autoboxing | int → Integer (automatic) |
| Unboxing | Integer → int (automatic) |
| Parse Methods | Integer.parseInt(), Double.parseDouble() |
| Equality | Use .equals(), not == |
| Null Danger | Unboxing null → NullPointerException |
| Cache Range | Integer caches -128 to 127 |
Question 1 of 5
Which of the following is a valid ArrayList declaration in Java?
Question 2 of 5
What is the output of the following code?
Integer a = 200;
Integer b = 200;
System.out.println(a == b);
Question 3 of 5
What does Integer.parseInt("37") return?
Question 4 of 5
What happens when this code runs?
Integer val = null;
int x = val;
Question 5 of 5
Consider this code:
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(10);
nums.add(20);
int sum = nums.get(0) + nums.get(1);
Which of the following best describes what happens?