Java Wrapper Classes with Examples

Java Wrapper Classes provide a way to use primitive data types as objects. Java is an object-oriented language. However, it includes primitive data types like int, char, boolean, and double for performance reasons. Wrapper classes solve the need to treat these primitives as objects.

java

This guide helps you understand Java wrapper classes. You will learn their purpose, how to use them, and their benefits.

What are Java Wrapper Classes?

A Java Wrapper Class is a class in the java.lang package. It encapsulates a primitive data type within an object. For every primitive data type, there is a corresponding wrapper class.

Here is a list of primitive types and their wrapper classes:

  • byte -> Byte
  • short -> Short
  • int -> Integer
  • long -> Long
  • float -> Float
  • double -> Double
  • char -> Character
  • boolean -> Boolean
Academy Pro

Java Programming Course

Learn Java the right way! Our course teaches you essential programming skills, from coding basics to complex projects, setting you up for success in the tech industry.

16.05 Hrs
3 Projects
Learn Java Programming

Why Use Wrapper Classes?

Wrapper classes are essential when you need to perform operations that only work with objects. Here are key reasons to use them:

  • Collections Framework: Java collections like ArrayList and HashMap store objects. They cannot directly store primitive types. Wrapper classes allow you to store primitive values in these collections.
  • Serialization: If you need to serialize a primitive value, you must wrap it in its corresponding wrapper class. Serialization works only with objects.
  • Synchronization: In multithreading, you can synchronize on objects. You cannot synchronize on primitive types. Wrapper objects allow you to use primitive values in synchronized blocks.
  • Utility Methods: Wrapper classes provide many useful static utility methods. These methods help convert values, parse strings, and perform other operations on primitive data. For example, Integer.parseInt("123") converts a string to an integer.

How Wrapper Classes Work

Java provides automatic conversion between primitive types and their wrapper class objects. This feature is called autoboxing and unboxing.

Autoboxing

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding wrapper class objects. When you assign a primitive value to a wrapper object, autoboxing occurs.

Example of Autoboxing:

Java

public class AutoboxingExample {
    public static void main(String[] args) {
        int primitiveInt = 100;
        Integer wrapperInt = primitiveInt; // Autoboxing: int to Integer

        System.out.println("Wrapper Integer: " + wrapperInt);
    }
}

In this example, the int value 100 is automatically converted to an Integer object.

Unboxing

Unboxing is the automatic conversion that the Java compiler makes between wrapper class objects and their corresponding primitive types. When you assign a wrapper object to a primitive variable, unboxing occurs.

Example of Unboxing:

Java

public class UnboxingExample {
    public static void main(String[] args) {
        Integer wrapperInt = 200;
        int primitiveInt = wrapperInt; // Unboxing: Integer to int

        System.out.println("Primitive int: " + primitiveInt);
    }
}

Here, the Integer object wrapperInt is automatically converted to an int value.

Creating Wrapper Objects

You can create wrapper objects explicitly using their constructors or valueOf() methods, though autoboxing often handles this for you. Using valueOf() is generally preferred for better performance, as it may cache frequently used values.

Example of Creating Wrapper Objects:

Java

public class CreateWrapperObjects {
    public static void main(String[] args) {
        // Using constructor (less common since Java 9 for some types)
        Integer intObj1 = new Integer(10);
        Character charObj1 = new Character('A');

        // Using valueOf() method (recommended)
        Integer intObj2 = Integer.valueOf(20);
        Double doubleObj2 = Double.valueOf(3.14);

        System.out.println("Integer object 1: " + intObj1);
        System.out.println("Character object 1: " + charObj1);
        System.out.println("Integer object 2: " + intObj2);
        System.out.println("Double object 2: " + doubleObj2);
    }
}

Utility Methods in Wrapper Classes

Wrapper classes provide many useful methods for type conversion and manipulation.

1. Parsing Strings to Primitives:

Each numeric wrapper class has a parseXxx() static method to convert a string to its corresponding primitive type.

Java

public class ParsingExample {
    public static void main(String[] args) {
        String strInt = "123";
        int numInt = Integer.parseInt(strInt); // Converts "123" to int

        String strDouble = "99.5";
        double numDouble = Double.parseDouble(strDouble); // Converts "99.5" to double

        System.out.println("Parsed int: " + numInt);
        System.out.println("Parsed double: " + numDouble);
    }
}

2. Converting Primitives to Strings:

You can convert a primitive or wrapper object to a string using String.valueOf() or the toString() method of the wrapper class.

Java

public class ToStringExample {
    public static void main(String[] args) {
        int num = 456;
        String strNum1 = String.valueOf(num); // int to String

        Integer wrapperNum = 789;
        String strNum2 = wrapperNum.toString(); // Integer object to String

        System.out.println("String from int: " + strNum1);
        System.out.println("String from Integer object: " + strNum2);
    }
}

3. Comparing Wrapper Objects:

When comparing wrapper objects, use the equals() method for value comparison. Using == checks for object identity (if they refer to the exact same object in memory).

Java

public class CompareWrapperObjects {
    public static void main(String[] args) {
        Integer a = 10;
        Integer b = 10;
        Integer c = 1000;
        Integer d = 1000;

        System.out.println("a == b: " + (a == b));       // True (autoboxed values -128 to 127 are cached)
        System.out.println("a.equals(b): " + a.equals(b)); // True

        System.out.println("c == d: " + (c == d));       // False (values outside cache range create new objects)
        System.out.println("c.equals(d): " + c.equals(d)); // True
    }
}

For Integer values between -128 and 127, Java caches the objects. This means a == b might return true for these values. For values outside this range, new objects are created, so c == d typically returns false. Always use equals() for value comparison.

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Academy Pro Subscription

Grab 50% off
on Top Courses - Free Trial Available

×
Scroll to Top