Wrapper Classes in Java
Wrapper Classes in Java – wrapper classes provide a way to use primitive data types (like int
, char
, boolean
, etc.) as objects. Each of the eight primitive data types has a corresponding wrapper class in the java.lang
package. These classes are:
boolean
->Boolean
char
->Character
byte
->Byte
short
->Short
int
->Integer
long
->Long
float
->Float
double
->Double
Wrapper classes are useful because they allow primitives to be used in contexts where objects are required, such as in collections (like ArrayList
, HashMap
, etc.) and in generic types.
Example of Wrapper Classes in Java
Let’s look at an example to understand how wrapper classes work.
Using Integer Wrapper Class
- Creating Wrapper Objects
public class WrapperExample {
public static void main(String[] args) {
// Using Integer wrapper class to create an Integer object from an int
int primitiveInt = 5;
Integer wrappedInt = Integer.valueOf(primitiveInt); // Boxing
// You can also use auto-boxing
Integer autoBoxedInt = primitiveInt;
System.out.println("Primitive int: " + primitiveInt);
System.out.println("Wrapped Integer: " + wrappedInt);
System.out.println("Auto-boxed Integer: " + autoBoxedInt);
}
}
Output:
Primitive int: 5
Wrapped Integer: 5
Auto-boxed Integer: 5
- Unboxing Wrapper Objects:
public class WrapperExample {
public static void main(String[] args) {
// Creating Integer object
Integer wrappedInt = Integer.valueOf(10);
// Converting Integer to int (unboxing)
int primitiveInt = wrappedInt.intValue(); // Unboxing
// You can also use auto-unboxing
int autoUnboxedInt = wrappedInt;
System.out.println("Wrapped Integer: " + wrappedInt);
System.out.println("Primitive int: " + primitiveInt);
System.out.println("Auto-unboxed int: " + autoUnboxedInt);
}
}
Output:
Wrapped Integer: 10
Primitive int: 10
Auto-unboxed int: 10
- Using Wrapper Classes with Collections:
import java.util.ArrayList;
public class WrapperExample {
public static void main(String[] args) {
// Creating an ArrayList to store Integer objects
ArrayList<Integer> integerList = new ArrayList<>();
// Adding primitive ints (auto-boxing to Integer)
integerList.add(1);
integerList.add(2);
integerList.add(3);
// Retrieving elements (auto-unboxing to int)
for (int number : integerList) {
System.out.println(number);
}
}
}
Output:
1
2
3
Key Points
- Boxing: Converting a primitive type into a corresponding wrapper object (e.g.,
int
toInteger
). - Unboxing: Converting a wrapper object back into its corresponding primitive type (e.g.,
Integer
toint
). - Auto-boxing and Auto-unboxing: Automatic conversion between primitive types and their corresponding wrapper objects.
Wrapper classes are essential for working with Java Collections Framework and other situations where objects are required rather than primitive types.