Wrapper Classes in Java
Wrapper classes convert primitive data types into objects.
Primitive to Wrapper Mapping
- int → Integer
- char → Character
- double → Double
- boolean → Boolean
Why Wrapper Classes Are Needed
- Collections store objects only
- Useful in frameworks
- Supports utility methods
- Required for generics
Real-World Example
ArrayList cannot directly store primitive int values, so Integer objects are used.
import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
System.out.println(list);
}
}Autoboxing
Automatic conversion of primitive to wrapper object.
Integer x = 100;Unboxing
Automatic conversion of wrapper object to primitive.
int y = x;Useful Methods
- Integer.parseInt()
- Double.parseDouble()
- Boolean.valueOf()
- Character.isDigit()
Interview Questions
- Why are wrapper classes required?
- What is autoboxing?
- Difference between int and Integer?
- Why collections cannot store primitive types?