Wrapper Class:
In Java, a Wrapper Class is a class that wraps (or “converts”) a primitive data type into an object.
This allows primitives to be treated as objects, so you can use them in Collections or call methods on them.
Primitive Types and Their Wrapper Classes:
Primitive Type Wrapper Class
byte -> Byte
short -> Short
int -> Integer
long -> Long
float -> Float
double -> Double
char -> Character
boolean -> Boolean
Why Wrapper Classes are Needed ?
1)Collections Requirement:
Collections (like ArrayList) can store objects only, not primitives.
ArrayList list = new ArrayList<>(); // int cannot be used directly
2)Utility Methods:
Wrapper classes provide useful methods, e.g., Integer.parseInt(), Double.valueOf().
3)Type Conversion:
Convert between strings and numbers.
int num = Integer.parseInt("123");
String str = Integer.toString(123);
4)Autoboxing and Unboxing:
Java automatically converts between primitives and wrapper objects:
Integer i = 10; // autoboxing
int j = i; // unboxing
Notes:
Primitive → basic data type, faster, stored in stack, no methods.
Wrapper Class → object version of primitive, stored in heap, can be used in Collections, has useful methods.
Why Objects are in Heap, Not Stack?
- Dynamic Size:
- Objects can vary in size at runtime.
- Stack memory is fixed and small → not suitable for variable-size objects.
- Long Lifetime:
- Objects may need to live beyond the method that created them.
- Stack variables disappear when the method ends.
- Heap objects can stay as long as they are referenced.
- Shared Access:
- Multiple methods or threads may access the same object.
- Stack memory is method-specific → cannot be shared.
- Garbage Collection:
- Heap allows automatic memory management using Garbage Collector.
- Stack is automatically cleared, but you cannot track object references globally.
Top comments (0)