Java Wrapper
In Java, a wrapper class is a special type of class that wraps
primitive data types into objects. This allows primitive values
(like
int, char, double,
etc.) to be treated as objects, which is useful in scenarios
where only objects are allowed, such as working with collections
like
ArrayList
.
Java provides built-in wrapper classes for each primitive type:
Integer
forint
Double
fordouble
Character
forchar
Boolean
forboolean
- And others, like
Float, Long, Byte,
andShort
Key Features:
- Object Representation – Wrapper classes allow primitive values to be represented as objects.
- Autoboxing & Unboxing – Java automatically converts primitive types to wrapper objects (autoboxing) and vice versa (unboxing).
- Useful Methods – Wrapper classes provide utility methods for converting, comparing, and manipulating values.
- Immutable – Once created, wrapper objects cannot be modified.
Example:
public class WrapperExample {
public static void main(String[] args) {
Integer num = 10; // Autoboxing (int → Integer)
int primitiveNum = num; // Unboxing (Integer → int)
System.out.println("Wrapper Class Value: " + num);
System.out.println("Primitive Value: " + primitiveNum);
}
}
Boxing and unboxing are concepts in Java related to converting between primitive data types and their corresponding wrapper classes.
Boxing (Autoboxing)
Boxing is the process of converting a primitive type into its corresponding wrapper class object. This happens automatically in Java when assigning a primitive value to a wrapper class.
Example of Boxing:
int num = 10;
Integer boxedNum = num; // Autoboxing: int → Integer
Here, num (a primitive int) is automatically converted into an
Integer
object (
boxedNum
).
Unboxing
Unboxing is the reverse process—converting a wrapper class object back into its primitive type.
Example of Unboxing:
Integer boxedNum = 20;
int num = boxedNum; // Unboxing: Integer → int
Here,
boxedNum
(an
Integer
object) is automatically converted back into a primitive
int
.
Why is Boxing & Unboxing Useful?
- Allows primitive types to be used in collections
(ArrayList, HashSet,
etc.), which only store objects. - Provides utility methods available in wrapper classes
(e.g.,
Integer.parseInt()
). - Makes code more flexible and readable.