Java Wrapper Class


In Java, primitive data types (such as int, char, double, etc.) are the building blocks for basic data manipulation. However, sometimes you may need to treat these primitive types as objects. This is where Java Wrapper Classes come into play.

A wrapper class in Java is a class that encapsulates a primitive data type into an object. Wrapper classes provide useful methods for converting between primitive types and objects, making it easier to use primitives in collections like ArrayList, HashMap, and others that can only hold objects.


What are Wrapper Classes?

Java provides a set of wrapper classes for each primitive data type. Each wrapper class corresponds to a primitive type and allows you to treat that primitive value as an object. The wrapper classes are:

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

Key Features of Wrapper Classes:

  • They allow primitive types to be treated as objects.
  • They provide utility methods to convert between primitive types and strings.
  • They allow primitive types to be stored in Java collections (like ArrayList, HashMap).
  • Wrapper classes are immutable (their values cannot be changed once set).

Why Do We Need Wrapper Classes?

Java's primitive types are efficient, but they have limitations when it comes to certain operations, such as:

  1. Storing in Collections: Java collections (like ArrayList) can only store objects, not primitive types.
  2. Autoboxing and Unboxing: When working with collections or certain API methods, primitive types need to be converted into objects. This is where autoboxing (conversion from primitive to object) and unboxing (conversion from object to primitive) come into play.

For example, in a List<Integer>, you can't store int values directly. You would need to use the wrapper class Integer instead.


Autoboxing and Unboxing

Java provides automatic conversion between primitive types and their corresponding wrapper classes. This is known as autoboxing and unboxing.

  • Autoboxing: The automatic conversion of a primitive type to its corresponding wrapper class.
  • Unboxing: The automatic conversion of a wrapper class object back to its corresponding primitive type.

Example of Autoboxing and Unboxing:

public class WrapperExample {
    public static void main(String[] args) {
        // Autoboxing: converting int to Integer
        int num = 10;
        Integer intWrapper = num;  // int to Integer (autoboxing)
        
        System.out.println("Autoboxed Integer: " + intWrapper);

        // Unboxing: converting Integer to int
        int unboxedNum = intWrapper;  // Integer to int (unboxing)
        
        System.out.println("Unboxed int: " + unboxedNum);
    }
}

Output:

Autoboxed Integer: 10
Unboxed int: 10

Explanation:

  • Autoboxing: The int variable num is automatically converted into an Integer object when assigned to intWrapper.
  • Unboxing: The Integer object intWrapper is automatically converted back to an int when assigned to unboxedNum.

Commonly Used Methods in Wrapper Classes

Each wrapper class provides several useful methods to interact with primitive data types. Here are some commonly used methods for each wrapper class:

Wrapper Class Common Methods
Integer parseInt(), toString(), valueOf(), compareTo()
Double parseDouble(), toString(), valueOf()
Character isDigit(), isLetter(), toLowerCase(), toString()
Boolean parseBoolean(), toString(), valueOf()

Example: Using Integer Methods

public class WrapperMethodsExample {
    public static void main(String[] args) {
        // Convert String to Integer
        String str = "100";
        Integer intValue = Integer.parseInt(str);
        System.out.println("Converted Integer: " + intValue);

        // Convert Integer to String
        String intString = intValue.toString();
        System.out.println("Integer as String: " + intString);

        // Compare two Integer values
        Integer num1 = 10, num2 = 20;
        int result = num1.compareTo(num2);
        System.out.println("Comparison result: " + result);  // Negative, because 10 < 20
    }
}

Output:

Converted Integer: 100
Integer as String: 100
Comparison result: -1

Explanation:

  • parseInt() converts a string to an integer.
  • toString() converts an integer to a string.
  • compareTo() compares two Integer objects.

Wrapper Classes and Collections

Java's collection framework (like ArrayList) cannot hold primitive types. However, you can store objects of wrapper classes instead. This allows you to work with primitive types in collections.

Example: Storing Wrapper Classes in an ArrayList

import java.util.ArrayList;

public class WrapperInCollections {
    public static void main(String[] args) {
        // Using ArrayList with Integer wrapper class
        ArrayList<Integer> list = new ArrayList<>();

        // Adding primitive int values (autoboxed to Integer)
        list.add(10);
        list.add(20);
        list.add(30);

        // Printing the ArrayList
        System.out.println("ArrayList: " + list);

        // Retrieving values from ArrayList (unboxing to int)
        int firstValue = list.get(0);
        System.out.println("First value: " + firstValue);
    }
}

Output:

ArrayList: [10, 20, 30]
First value: 10

Explanation:

  • Autoboxing: The int values are automatically converted to Integer objects when added to the ArrayList.
  • Unboxing: The Integer object is automatically converted back to int when retrieved from the ArrayList.

Performance Considerations

While wrapper classes provide great flexibility, there are some performance trade-offs to consider:

  • Memory Usage: Objects consume more memory compared to primitive types. Using wrapper classes increases memory usage, especially in large collections.
  • Processing Time: The process of autoboxing and unboxing adds slight overhead in terms of performance, particularly in tight loops or critical sections of code.

For scenarios where performance and memory are crucial, you may want to minimize the use of wrapper classes and stick with primitives where possible.