What is Wrapper Class in Java: Explanation and Examples
wrapper class in Java is a special class that allows primitive data types like int or double to be treated as objects. It "wraps" the primitive value inside an object so you can use it where objects are required, such as in collections.How It Works
Think of a wrapper class as a gift box that holds a simple item inside. The item is a primitive value like a number, but the box lets you carry it around as an object. Java has eight wrapper classes, one for each primitive type, such as Integer for int and Double for double.
This wrapping is useful because Java collections like ArrayList can only store objects, not primitives. So, the wrapper class acts like a bridge, converting a primitive into an object and back again when needed. This process is called boxing (wrapping) and unboxing (unwrapping).
Example
This example shows how to wrap an int value into an Integer object and then unwrap it back to int.
public class WrapperExample { public static void main(String[] args) { int num = 10; // primitive int Integer wrappedNum = Integer.valueOf(num); // boxing: int to Integer int unwrappedNum = wrappedNum.intValue(); // unboxing: Integer to int System.out.println("Wrapped Integer: " + wrappedNum); System.out.println("Unwrapped int: " + unwrappedNum); } }
When to Use
Use wrapper classes when you need to work with primitives as objects. For example, Java collections like ArrayList cannot store primitive types directly, so you use wrapper classes to store numbers or booleans.
Wrapper classes also provide useful methods to convert between types, parse strings, or handle null values safely. They are essential when interacting with APIs that require objects instead of primitives.
Key Points
- Wrapper classes wrap primitive types into objects.
- They enable primitives to be used in collections and APIs requiring objects.
- Java automatically converts between primitives and wrappers (autoboxing/unboxing).
- Each primitive type has a corresponding wrapper class, like
intandInteger.