Java Wrapper Classes


In Java, everything revolves around objects. However, primitive data types like int, char, float, and boolean are not objects. They are simple values that perform faster but cannot be used where objects are required, such as in collections like ArrayList or HashMap. To bridge this gap, Java provides Wrapper Classes, which convert primitive types into objects.

This concept makes your code more flexible and object-oriented. Let’s explore what wrapper classes are, how they work, and why they are so useful.

What Are Wrapper Classes in Java?

Wrapper classes are built-in classes in Java that represent primitive data types as objects. They “wrap” a primitive value inside an object so that it can be treated like any other object in Java.

For example:

  • intInteger

  • charCharacter

  • doubleDouble

  • booleanBoolean

Each primitive data type has a corresponding wrapper class in the java.lang package.

List of Wrapper Classes in Java

Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

All wrapper classes are immutable, which means once a wrapper object is created, its value cannot be changed.

Why Use Wrapper Classes?

Wrapper classes are needed when:

  1. Using collections — For example, ArrayList can store only objects, not primitive values.

  2. Performing object-oriented programming — They allow primitives to behave like objects.

  3. Converting between strings and numbers — Methods like Integer.parseInt() and Double.valueOf() are very useful for such conversions.

  4. Handling null values — Primitives can’t hold null, but wrapper objects can.

  5. Using Java features like Generics and Streams, which work only with objects.

Example: Primitive vs Wrapper

Let’s look at a simple example:

public class WrapperExample {
    public static void main(String[] args) {
        int num = 10; // primitive
        Integer obj = Integer.valueOf(num); // wrapping primitive into object

        System.out.println("Primitive value: " + num);
        System.out.println("Wrapper object: " + obj);
    }
}

Output:

Primitive value: 10
Wrapper object: 10

Here, Integer.valueOf(num) converts the primitive int into an Integer object.

Autoboxing and Unboxing in Java

Java introduced Autoboxing and Unboxing in JDK 1.5 to make working with wrapper classes easier.

1. Autoboxing

Autoboxing means automatically converting a primitive type into its corresponding wrapper class object.

Example:

public class AutoBoxingExample {
    public static void main(String[] args) {
        int a = 5;
        Integer obj = a; // autoboxing
        System.out.println("Autoboxed value: " + obj);
    }
}

Here, Java automatically wraps int a into an Integer object without needing Integer.valueOf() explicitly.

2. Unboxing

Unboxing is the reverse of autoboxing. It automatically converts a wrapper object back into its primitive type.

Example:

public class UnboxingExample {
    public static void main(String[] args) {
        Integer obj = 20;
        int num = obj; // unboxing
        System.out.println("Unboxed value: " + num);
    }
}

Here, the Integer object obj is automatically converted into a primitive int.

Autoboxing and Unboxing in Collections

One of the most common uses of wrapper classes is with collections. Since collections like ArrayList cannot store primitive types, autoboxing and unboxing make it easy to use them.

Example:

import java.util.ArrayList;

public class WrapperCollectionExample {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();

        // Autoboxing: int to Integer
        list.add(10);
        list.add(20);
        list.add(30);

        // Unboxing: Integer to int
        for (int num : list) {
            System.out.println(num);
        }
    }
}

You don’t have to manually convert between int and Integer — Java does it automatically.

Converting Between Primitives and Strings

Wrapper classes also provide methods to convert between strings and numbers.

Convert String to int

public class StringToInt {
    public static void main(String[] args) {
        String s = "100";
        int num = Integer.parseInt(s);
        System.out.println(num);
    }
}

Convert int to String

public class IntToString {
    public static void main(String[] args) {
        int num = 200;
        String s = Integer.toString(num);
        System.out.println(s);
    }
}

These conversions are common when working with user input or file data.

Wrapper Class Utility Methods

Wrapper classes provide several static methods for conversions and data handling:

Method Description
Integer.parseInt(String s) Converts string to int
Double.parseDouble(String s) Converts string to double
Integer.valueOf(int i) Converts primitive int to Integer
Integer.toString(int i) Converts int to String
Character.isDigit(char ch) Checks if character is a digit
Character.toUpperCase(char ch) Converts character to uppercase

These utility methods are very useful in real-world applications.

Comparing Wrapper Objects

Wrapper objects can be compared using .equals() for value comparison and == for reference comparison.

Example:

public class CompareWrapper {
    public static void main(String[] args) {
        Integer a = 100;
        Integer b = 100;
        Integer c = new Integer(100);

        System.out.println(a == b);      // true (cached values)
        System.out.println(a == c);      // false (different objects)
        System.out.println(a.equals(c)); // true (same value)
    }
}

Note: For small integer values (-128 to 127), Java caches Integer objects, so comparisons may sometimes return true with ==.

Null Handling in Wrapper Classes

Unlike primitives, wrapper classes can store null values. This can be helpful but also risky because unboxing a null object will cause a NullPointerException.

Example:

public class NullUnboxing {
    public static void main(String[] args) {
        Integer obj = null;
        try {
            int num = obj; // unboxing null
        } catch (NullPointerException e) {
            System.out.println("Cannot unbox a null value!");
        }
    }
}

Always check for null before unboxing wrapper objects.

Advantages of Wrapper Classes

  • Allow primitives to be used where objects are required

  • Useful in collections and generics

  • Provide conversion methods between types and strings

  • Offer additional utility methods for validation

  • Support autoboxing and unboxing for cleaner code

Summary of the Tutorial

Wrapper classes are an essential part of Java that let you use primitive data types as objects. They make working with collections, generics, and advanced frameworks much easier.

Key takeaways:

  • Every primitive has a corresponding wrapper class.

  • Autoboxing and unboxing simplify conversions.

  • Wrapper objects are immutable.

  • Use .equals() for comparing values instead of ==.

Wrapper classes help combine the performance of primitives with the flexibility of objects, which is a core concept in modern Java programming.


Practice Questions

  1. Write a Java program to convert a primitive int into an Integer object using both valueOf() and autoboxing.

  2. Create a Java program that converts a double value into a Double object and then back into a primitive double.

  3. Write a program that converts a String value "250" into an int using Integer.parseInt(), performs an addition of 50, and displays the result.

  4. Create a program to demonstrate autoboxing and unboxing using an ArrayList<Integer>.

  5. Write a Java program to check whether a given character is a digit or a letter using the Character wrapper class.

  6. Write a program to compare two Integer objects — one created using autoboxing and another using new Integer() — and show the result of both == and .equals() comparisons.

  7. Create a program that takes a numeric input from the user (as a String) and converts it to float and double using wrapper methods.

  8. Write a Java program that converts an int into a String using both Integer.toString() and String.valueOf().

  9. Write a program that demonstrates what happens when you try to unbox a null Integer object. Handle the exception properly.

  10. Create a Java program that uses wrapper methods to check whether a given character is uppercase, lowercase, or a whitespace.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top