Skip to content
C

Wrapper Classes

Wrapper classes let you use primitive data types (like int, double, boolean) as objects. Each primitive type has a corresponding wrapper class — for example, int becomes Integer, and double becomes Double.


1. What are Wrapper Classes?

Wrapper classes let you use primitive data types (like int, double, boolean) as objects. Each primitive type has a corresponding wrapper class — for example, int becomes Integer, and double becomes Double.

2. Why is it used?

Many parts of Java, especially the Collection Framework, work only with objects, not primitives. Wrapper classes let you store primitive-like values inside collections such as ArrayList<Integer>, which wouldn't accept a plain int directly.

3. Real-Life Example

Think of putting loose coins into a small pouch before placing them into a large storage locker that only accepts pouches, not loose coins. The wrapper class is like that pouch, letting a plain primitive value be "accepted" wherever an object is required.

4. Syntax

java
int a = 10; Integer wrappedA = a; // autoboxing int unwrappedA = wrappedA; // unboxing

5. Example Program

java
import java.util.ArrayList; public class WrapperDemo { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(10); // int auto-converted to Integer int value = numbers.get(0); // Integer auto-converted back to int System.out.println("Value: " + value); } }

Output:

Value: 10

6. Key Points to Remember

  • Each of Java's 8 primitive types has one corresponding wrapper class.
  • Autoboxing is automatic conversion from primitive to wrapper; unboxing is the reverse.
  • Wrapper classes also provide useful utility methods, like Integer.parseInt() to convert a String into an int.