Topic 87 of 119 9. Java Wrapper Classes Interactive Tutorial

Java Wrapper Classes: Boxing, Unboxing, and Object Representations of Primitives

10 mins read Last updated: 22 Aug 2026 30,051 views

Direct Answer & Core Concept

Java has two important categories of data types: primitive types and reference types.

Primitive types such as int, double, char, and boolean store simple values directly. However, many Java APIs work with objects rather than primitive values.

Wrapper classes solve this problem by providing object representations of primitive data types.

For example:

Main.java
Run Online
int number = 100;
Integer objectNumber = 100;

Here, int is a primitive type, while Integer is the wrapper class for int.

Wrapper classes are especially important when working with collections, generics, utility methods, nullable values, and object-based APIs.

Detailed Explanation & Mechanics

What Are Wrapper Classes in Java?

A wrapper class is a class that represents a primitive data type as an object.

Java provides wrapper classes for all eight primitive types.

Primitive TypeWrapper Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

There is no wrapper class named Void for the primitive void in the same sense as the eight primitive value types, although Java provides java.lang.Void as a utility wrapper type representing void.


Why Do We Need Wrapper Classes?

Primitive values are efficient, but they are not objects.

For example:

You cannot use int directly where an API requires an object.

Wrapper classes provide object representations:

This becomes particularly important with Java collections.

For example, this is invalid:

Java generics require reference types.

Instead, use:

Example:

Main.java
Run Online
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);

Java automatically converts the primitive values to Integer objects when needed.


The Eight Wrapper Classes

1. Byte

The wrapper class for byte is Byte.

Main.java
Run Online
byte value = 10;
Byte object = 10;

Byte is useful when a byte value needs to be represented as an object.


2. Short

The wrapper class for short is Short.

Main.java
Run Online
short value = 100;
Short object = 100;

3. Integer

The wrapper class for int is Integer.

Main.java
Run Online
int value = 100;
Integer object = 100;

Integer is one of the most commonly used wrapper classes.


4. Long

The wrapper class for long is Long.

Main.java
Run Online
long value = 100000L;
Long object = 100000L;

5. Float

The wrapper class for float is Float.

Main.java
Run Online
float value = 10.5f;
Float object = 10.5f;

6. Double

The wrapper class for double is Double.

Main.java
Run Online
double value = 20.50;
Double object = 20.50;

7. Character

The wrapper class for char is Character.

Main.java
Run Online
char letter = 'A';
Character object = 'A';

Character also provides many useful methods for working with characters.

For example:

Main.java
Run Online
System.out.println(Character.isLetter('A'));
System.out.println(Character.isDigit('5'));

8. Boolean

The wrapper class for boolean is Boolean.

Main.java
Run Online
boolean active = true;
Boolean object = true;

Boolean also provides utility methods for parsing and converting boolean values.


Primitive vs Wrapper Class

Consider:

Main.java
Run Online
int number = 100;
Integer objectNumber = 100;

The difference is important.

FeatureintInteger
TypePrimitiveReference type
StoresPrimitive valueObject representation
Can be nullNoYes
Works with genericsNoYes
Has methodsNo instance methodsYes
Object typeNoYes
Memory behaviorGenerally more lightweightObject/reference overhead

For ordinary numeric calculations, primitives are often the natural choice.

Wrapper classes become useful when an object is required.


What Is Boxing?

Boxing means converting a primitive value into its corresponding wrapper object.

For example:

Main.java
Run Online
int number = 10;
Integer object = Integer.valueOf(number);

The primitive int value is converted into an Integer object.


What Is Autoboxing?

Java can perform boxing automatically.

This is called autoboxing.

Main.java
Run Online
int number = 10;
Integer object = number;

Java automatically converts the int value to an Integer.

Conceptually, this is similar to:

Main.java
Run Online
Integer object = Integer.valueOf(number);

Autoboxing makes code involving primitives and objects much easier to write.


Example of Autoboxing

Main.java
Run Online
public class Main {
    public static void main(String[] args) {
        int number = 50;
        Integer object = number;
        System.out.println(object);
    }
}

Output:

The conversion from int to Integer happens automatically.


What Is Unboxing?

Unboxing means converting a wrapper object back into its corresponding primitive value.

For example:

Main.java
Run Online
Integer object = 100;
int number = object.intValue();

The Integer object is converted into an int.


What Is Auto-Unboxing?

Java can also perform unboxing automatically.

Main.java
Run Online
Integer object = 100;
int number = object;

Java automatically extracts the primitive int value.

Conceptually, it is similar to:

Main.java
Run Online
int number = object.intValue();

Boxing and Unboxing Together

You can move between primitive and wrapper types automatically.

Main.java
Run Online
int number = 100;
Integer object = number;
// Autoboxing
int result = object;
// Auto-unboxing

The flow is:

Main.java
Run Online
int↓Autoboxing↓Integer↓Auto-unboxing↓int

Boxing and Unboxing Example

Main.java
Run Online
public class Main {
    public static void main(String[] args) {
        int number = 25;
        // Autoboxing
        Integer object = number;
        // Auto-unboxing
        int result = object;
        System.out.println("Primitive: " + number);
        System.out.println("Object: " + object);
        System.out.println("Result: " + result);
    }
}

Output:

Main.java
Run Online
Primitive: 25Object: 25Result: 25

Wrapper Classes and Collections

One of the most important uses of wrapper classes is with Java collections.

Generics cannot use primitive types directly.

This is invalid:

Use:

Example:

Main.java
Run Online
import java.util.ArrayList;
import java.util.List;
public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        System.out.println(numbers);
    }
}

Output:

Here:

uses autoboxing to convert 10 from int to Integer.


Wrapper Classes with Generics

Consider a generic method:

Main.java
Run Online
public static void printValue(Integer value) {
    System.out.println(value);
}

You can call it using:

Main.java
Run Online
int number = 100;
printValue(number);

Java automatically boxes the primitive:

Main.java
Run Online
int↓Integer↓Method argument

This is one reason autoboxing is convenient.


Wrapper Classes Can Store null

Primitive types cannot represent null.

For example:

This is invalid.

But:

is valid.

This distinction can be important when a value is optional or missing.

Example:

Main.java
Run Online
Integer age = null;
if (age == null) {
    System.out.println("Age not provided");
}

Important Danger: Unboxing null

Although wrapper objects can be null, automatic unboxing of a null wrapper causes a NullPointerException.

Example:

Main.java
Run Online
Integer number = null;
int value = number;

This fails because Java needs to extract an int from a null Integer.

A safer approach is:

Main.java
Run Online
Integer number = null;
if (number != null) {
    int value = number;
}

Or use an appropriate default when the application's logic requires one.


Wrapper Class Methods

Wrapper classes provide useful methods for conversion and comparison.

For example:

Main.java
Run Online
String text = "123";
int number = Integer.parseInt(text);
System.out.println(number);

Output:

The Integer wrapper class provides several useful static methods.


Parsing Strings into Numbers

Wrapper classes are commonly used to convert strings into primitive values.

String to int

Main.java
Run Online
int number = Integer.parseInt("100");

String to long

Main.java
Run Online
long number = Long.parseLong("100000");

String to double

Main.java
Run Online
double number = Double.parseDouble("25.50");

String to float

Main.java
Run Online
float number = Float.parseFloat("12.5");

String to boolean

Main.java
Run Online
boolean result = Boolean.parseBoolean("true");

Converting Numbers to Strings

Wrapper classes can also help convert values to strings.

For example:

Main.java
Run Online
int number = 100;
String text = Integer.toString(number);

You can also use:

Main.java
Run Online
String text = String.valueOf(number);

The latter is often useful when working with values of different types.


Integer.valueOf() vs parseInt()

These two methods are commonly confused.

parseInt()

Main.java
Run Online
int number = Integer.parseInt("100");

It returns a primitive int.

valueOf()

Main.java
Run Online
Integer number = Integer.valueOf("100");

It returns an Integer object.

So:

Main.java
Run Online
parseInt()↓intvalueOf()↓Integer

Example: parseInt vs valueOf

Main.java
Run Online
public class Main {
    public static void main(String[] args) {
        int primitive = Integer.parseInt("100");
        Integer object = Integer.valueOf("100");
        System.out.println(primitive);
        System.out.println(object);
    }
}

Both represent the number 100, but their types are different.


Wrapper Classes and Comparison

Be careful when comparing wrapper objects.

Consider:

Main.java
Run Online
Integer a = 100;
Integer b = 100;
System.out.println(a == b);

The result may be true because of wrapper object caching for certain values.

But you should not use == as a general way to compare wrapper values.

Prefer:

Main.java
Run Online
System.out.println(a.equals(b));

when comparing wrapper objects by value.


Integer Caching

Some wrapper classes may cache commonly used values.

For Integer, Java specifies caching for certain commonly used integer values, and implementations may cache additional values.

Therefore:

Main.java
Run Online
Integer a = 100;
Integer b = 100;
System.out.println(a == b);

can produce:

But:

Main.java
Run Online
Integer a = 1000;
Integer b = 1000;
System.out.println(a == b);

should not be used to determine whether the numeric values are equal.

Use:

instead.


Correct Wrapper Comparison

Incorrect general approach

Main.java
Run Online
Integer a = 1000;
Integer b = 1000;
if (a == b) {
    System.out.println("Equal");
}

== compares object references when both operands are wrapper objects.

Better approach

Main.java
Run Online
if (a.equals(b)) {
    System.out.println("Equal");
}

Or, when nulls are possible:

Main.java
Run Online
if (Objects.equals(a, b)) {
    System.out.println("Equal");
}

Wrapper Classes Are Immutable

Wrapper objects such as Integer, Long, Double, Boolean, and Character are immutable.

For example:

Main.java
Run Online
Integer number = 10;
number = 20;

This does not modify the existing Integer object from 10 into 20.

Instead, the variable is assigned another value/object representation.

This is important when understanding object behavior and memory.


Wrapper Classes and Arithmetic

Java can automatically unbox wrapper objects during arithmetic.

Main.java
Run Online
Integer a = 10;
Integer b = 20;
int result = a + b;
System.out.println(result);

Java effectively unboxes the values before performing the arithmetic.

Conceptually:

Main.java
Run Online
Integer → intInteger → int↓Addition↓int

Mixed Primitive and Wrapper Arithmetic

You can also mix primitive and wrapper values.

Main.java
Run Online
Integer number = 10;
int value = 20;
int result = number + value;
System.out.println(result);

The wrapper value is automatically unboxed.


Wrapper Classes and Method Arguments

Suppose a method expects an Integer:

Main.java
Run Online
public static void printNumber(Integer number) {
    System.out.println(number);
}

You can pass an int:

Main.java
Run Online
int value = 50;
printNumber(value);

Autoboxing converts the primitive to the required wrapper object.


Wrapper Classes and Return Values

A method can return a wrapper object:

Main.java
Run Online
public static Integer getNumber() {
    return 100;
}

The int literal 100 is automatically boxed into an Integer.

You can also return a primitive from a method declared to return a wrapper type.


Wrapper Classes in Real Applications

Wrapper classes commonly appear in:

  • Collections

  • Generics

  • Database applications

  • DTOs

  • API request and response models

  • Optional values

  • Serialization

  • Frameworks

  • Utility methods

  • Object-oriented APIs

For example, an API response may represent an optional numeric field using:

instead of:

because Integer can represent "not provided" using null.


Wrapper Classes and Database Values

Database columns can sometimes contain NULL.

A Java object model may therefore use:

because it can represent:

or:

A primitive:

cannot directly represent null.

The correct choice depends on the application's data model.


Performance Considerations

Primitive values are generally more lightweight than wrapper objects.

For example:

Main.java
Run Online
int[] numbers = new int[1000000];

and:

Main.java
Run Online
Integer[] numbers = new Integer[1000000];

have different memory and performance characteristics.

A primitive array stores primitive values directly.

A wrapper array stores references to objects, with object overhead involved.

Therefore, when object semantics are not required, primitives can be preferable for performance-sensitive code.


Avoid Unnecessary Boxing

Consider:

Main.java
Run Online
Integer total = 0;
for (int i = 0;
i < 1000000;
i++) {
    total = total + i;
}

This involves repeated unboxing and boxing.

For straightforward numerical calculations, a primitive is often more appropriate:

Main.java
Run Online
int total = 0;
for (int i = 0;
i < 1000000;
i++) {
    total += i;
}

The best choice depends on the application's requirements.


Common Wrapper Classes Example

Main.java
Run Online
public class Main {
    public static void main(String[] args) {
        Byte byteValue = 10;
        Short shortValue = 20;
        Integer intValue = 30;
        Long longValue = 40L;
        Float floatValue = 50.5f;
        Double doubleValue = 60.5;
        Character charValue = 'A';
        Boolean booleanValue = true;
        System.out.println(byteValue);
        System.out.println(shortValue);
        System.out.println(intValue);
        System.out.println(longValue);
        System.out.println(floatValue);
        System.out.println(doubleValue);
        System.out.println(charValue);
        System.out.println(booleanValue);
    }
}

This demonstrates the eight primitive wrapper classes.


Boxing and Unboxing Summary

Boxing

Primitive → Wrapper

Main.java
Run Online
int number = 10;
Integer object = number;

Unboxing

Wrapper → Primitive

Main.java
Run Online
Integer object = 10;
int number = object;

Explicit boxing

Main.java
Run Online
Integer object = Integer.valueOf(10);

Explicit unboxing

Main.java
Run Online
int number = object.intValue();

Wrapper Classes Cheat Sheet

PrimitiveWrapperParse Method
byteByteByte.parseByte()
shortShortShort.parseShort()
intIntegerInteger.parseInt()
longLongLong.parseLong()
floatFloatFloat.parseFloat()
doubleDoubleDouble.parseDouble()
charCharacterCharacter conversion methods
booleanBooleanBoolean.parseBoolean()

Common Mistakes with Wrapper Classes

Mistake 1: Using primitives in generics

Incorrect:

Correct:


Mistake 2: Comparing wrappers with ==

Avoid relying on:

Main.java
Run Online
Integer a = 1000;
Integer b = 1000;
a == b

Use:

or:

when null safety is required.


Mistake 3: Unboxing null

This can cause:

Main.java
Run Online
Integer value = null;
int number = value;

Result:

Check for null before unboxing when null is possible.


Mistake 4: Using wrappers unnecessarily in performance-sensitive calculations

If you simply need numerical calculations, a primitive may be more appropriate.

Use wrapper classes when object behavior, generics, nullability, or an API requirement makes them useful.


Best Practices

Use primitives for ordinary calculations

Main.java
Run Online
int count = 100;
double price = 50.25;

Use wrappers when an object is required

Use wrappers when null has semantic meaning

Compare wrapper values properly

or:

Understand automatic conversion

Know when Java performs:

and:

This helps prevent unexpected NullPointerException and performance issues.


Frequently Asked Questions

What are wrapper classes in Java?

Wrapper classes are object representations of Java primitive data types. Examples include Integer for int, Double for double, and Boolean for boolean.

What is autoboxing?

Autoboxing is Java's automatic conversion of a primitive value into its corresponding wrapper object.

What is unboxing?

Unboxing is the automatic conversion of a wrapper object into its corresponding primitive value.

Main.java
Run Online
Integer number = 10;
int value = number;

Why are wrapper classes needed?

They allow primitive values to be used where Java requires objects, such as generic collections.

Can wrapper classes contain null?

Yes. Wrapper references can be null, while primitive variables cannot.

What happens when a null wrapper is unboxed?

Java cannot extract a primitive value from null, so automatic unboxing causes a NullPointerException.

Why can't List<int> be used?

Java generics work with reference types, not primitive types. Use List<Integer> instead.

What is the difference between Integer.parseInt() and Integer.valueOf()?

parseInt() returns a primitive int, while valueOf() returns an Integer object.

Should wrapper objects be compared using ==?

Generally, no. == compares object references when both operands are wrapper objects. Use .equals() or Objects.equals() for value comparison.

Are wrapper classes immutable?

Yes. Standard primitive wrapper classes such as Integer, Long, Double, Character, and Boolean are immutable.


Practice Questions

  1. What is a wrapper class in Java?

  2. List all eight primitive wrapper classes.

  3. What is boxing?

  4. What is autoboxing?

  5. What is unboxing?

  6. What is auto-unboxing?

  7. Why does Java use Integer instead of int in collections?

  8. What happens when an Integer containing null is unboxed?

  9. What is the difference between parseInt() and valueOf()?

  10. Why should wrapper objects generally not be compared using ==?

  11. What does Integer.valueOf() return?

  12. Can wrapper classes represent null?

  13. Why might a primitive be preferred over a wrapper in performance-sensitive code?

  14. What happens when wrapper objects are used in arithmetic expressions?

  15. Why are wrapper classes considered immutable?


Quick Revision

Remember the basic relationship:

Main.java
Run Online
Primitive↓Autoboxing↓Wrapper Object↓Auto-unboxing↓Primitive

Examples:

Main.java
Run Online
int a = 10;
Integer b = a;
// Autoboxing
int c = b;
// Auto-unboxing

The most commonly used wrapper classes are:

Main.java
Run Online
int → Integerlong → Longdouble → Doublefloat → Floatshort → Shortbyte → Bytechar → Characterboolean → Boolean

The key rule is simple:

Use primitives for simple values and calculations; use wrapper classes when Java needs an object, such as in generics, collections, nullable fields, or object-based APIs.

Graphics and Design Ideas

Graphic 1: Primitive to Wrapper Conversion

Create a simple visual:

Architecture Diagram
┌─────────────┐
│     int     │
│     100     │
└──────┬──────┘
       │
       │ Autoboxing
↓
┌─────────────┐
│   Integer   │
│    Object   │
└──────┬──────┘
       │
       │ Auto-unboxing
↓
┌─────────────┐
│     int     │
│     100     │
└─────────────┘

Graphic 2: Primitive → Wrapper Map

Show all eight conversions:

Main.java
Run Online
byte → Byteshort → Shortint → Integerlong → Longfloat → Floatdouble → Doublechar → Characterboolean → Boolean

Graphic 3: Collections Example

Visualize:

Main.java
Run Online
int↓Autoboxing↓Integer↓List<Integer>↓[10, 20, 30]

This clearly explains why wrapper classes are required with Java generics.

Graphic 4: Null Difference

Show:

Main.java
Run Online
int↓Cannot store nullInteger↓Can store null

Then highlight:

Main.java
Run Online
Integer value = null;
int number = value;
↓NullPointerException

Graphic 5: == vs .equals()

Create a comparison card:

Main.java
Run Online
Integer a = 1000;
Integer b = 1000;
a == b↓Reference comparisona.equals(b)↓Value comparison

This is a useful visual for one of the most common Java wrapper-class mistakes.

Runnable Code Example: Java Wrapper Classes

Java 17+
Main.java
Run Online
public class WrapperClassDemo {
    public static void main(String[] args) {
        // Static factory method (preferred over deprecated new Integer())
        Integer num = Integer.valueOf(100);
        int parsed = Integer.parseInt("450");
        System.out.println("Max Integer: " + Integer.MAX_VALUE);
        System.out.println("Binary String of 450: " + Integer.toBinaryString(parsed));
    }
}

Common Java Technical Interview Questions & Answers

Interview Prep
Q1

Why were wrapper constructors like new Integer(100) deprecated in Java 9?

Because new Integer() bypasses the JVM IntegerCache and allocates unnecessary heap objects; Integer.valueOf() is preferred.
Q2

What is the IntegerCache in Java?

The JVM caches Integer objects for values in the range -128 to 127 to reuse instances and save memory.

Key Takeaways, Best Practices & Clean Code Rules

Java Best Practice & Production Rules

Always use static factory methods like Integer.valueOf() or Double.valueOf() instead of deprecated constructors.