Wrapper Classes
Java is an object-oriented programming language, which means everything should theoretically be an object. However, for performance reasons, Java provides eight primitive data types (int, char, double, boolean, etc.) that are not objects.
A Wrapper class in Java provides the mechanism to convert these primitive data types into object equivalents. These wrapper classes are part of the java.lang package.
The Eight Wrapper Classes
Here is the mapping of primitive types to their corresponding Wrapper classes:
| Primitive Type | Wrapper Class |
|---|---|
boolean | Boolean |
char | Character |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
Why Do We Need Wrapper Classes?
- Collections Framework: Java's Collection framework (like
ArrayList,HashMap,HashSet) strictly works with Objects. You cannot store primitive types likeintinside anArrayList. You must use theIntegerwrapper class. - Utility Methods: Wrapper classes provide helpful constants (like
Integer.MAX_VALUE) and utility methods (likeInteger.parseInt(String)) to manipulate primitive data. - Synchronization: Multithreading synchronization requires an object lock. Primitives cannot be used for locks.
Autoboxing and Unboxing
Before Java 5, developers had to manually convert primitives to wrapper objects and vice-versa. Java 5 introduced Autoboxing and Unboxing to make this process automatic and seamless.
1. Autoboxing
The automatic conversion of a primitive data type into its corresponding Wrapper class object by the Java compiler is known as Autoboxing.
public class LabWrapper1 {
public static void main(String args[]) {
int primitiveInt = 50;
// Manual boxing (Prior to Java 5)
Integer obj1 = Integer.valueOf(primitiveInt);
// Autoboxing (Java 5 and later)
Integer obj2 = primitiveInt;
System.out.println("Primitive: " + primitiveInt);
System.out.println("Autoboxed Object: " + obj2);
}
}
2. Unboxing
The automatic conversion of a Wrapper class object back into its corresponding primitive data type is known as Unboxing.
public class LabWrapper2 {
public static void main(String args[]) {
Integer obj = new Integer(100);
// Manual unboxing
int primitive1 = obj.intValue();
// Unboxing (Automatic)
int primitive2 = obj;
System.out.println("Object: " + obj);
System.out.println("Unboxed Primitive: " + primitive2);
}
}
[!NOTE] Even though Autoboxing and Unboxing happen automatically, they still consume CPU cycles under the hood. Avoid unnecessary boxing/unboxing in tight loops for high-performance applications!