DEV Community

Jayashree
Jayashree

Posted on

Wrapper Classes in Java – A Simple Guide

When we start learning Java, we mostly work with primitive data types like int, char, double, etc. These are fast and efficient. But at some point, we run into situations where primitives alone are not enough. That’s where wrapper classes come into the picture.

What is a Wrapper Class?

A wrapper class is used to convert a primitive data type into an object.

In simple terms, it “wraps” a primitive value inside an object.

For example:

  • int → Integer
  • char → Character
  • double → Double
  • boolean → Boolean

So instead of working with raw values, we can work with objects.

Why Do We Need Wrapper Classes?

You might wonder — why not just use primitives?

Good question. Here are the main reasons:

1. Collections work only with objects

Java collections like ArrayList cannot store primitive types.

ArrayList<int> list;   //  Not allowed
ArrayList<Integer> list; //  Allowed
Enter fullscreen mode Exit fullscreen mode

So we use wrapper classes to store values in collections.

2. Utility Methods

Wrapper classes provide useful methods like:

Integer.parseInt("123");   // converts String to int
Double.valueOf("10.5");    // converts String to Double
Enter fullscreen mode Exit fullscreen mode

These methods make data conversion easy.

3. Object-Oriented Features

Sometimes we need objects instead of primitives—for example, when working with APIs, frameworks, or generics.

Wrapper classes help us follow object-oriented programming concepts.

Autoboxing and Unboxing

Java automatically converts between primitives and wrapper classes.

Autoboxing (primitive → object)
Integer num = 10; // int → Integer

Unboxing (object → primitive)
Integer num = 10;
int value = num; // Integer → int

This makes coding easier and cleaner.

Where Are Wrapper Objects Stored?

Primitive values → stored in stack memory
Wrapper objects → stored in heap memory
Reference variables → stored in stack

Example:

Integer a = 10;

Here:

a is stored in stack
The actual object (10) is stored in heap
Special Case: Integer Caching

Java caches values between -128 to 127.

Integer x = 100;
Integer y = 100;

System.out.println(x == y); // true
Enter fullscreen mode Exit fullscreen mode

Because Java reuses the same object from memory.

But:

Integer x = 200;
Integer y = 200;

System.out.println(x == y); // false
Enter fullscreen mode Exit fullscreen mode

Here, new objects are created.

Final Thoughts

Wrapper classes play a very important role in Java. Even though primitives are faster, wrapper classes give flexibility, especially when working with collections, APIs, and object-based operations.

If you are preparing for interviews, understanding wrapper classes, autoboxing, and memory behavior is a must.

Top comments (0)