Java - Wrapper Classes in Java
Wrapper classes in Java are special classes that convert primitive data types into objects. Java provides primitive data types such as int, char, double, float, boolean, byte, short, and long for storing simple values. However, many Java features and APIs work only with objects. Wrapper classes solve this limitation by providing an object representation for every primitive data type.
1. Primitive Data Types and Their Wrapper Classes
Each primitive data type has a corresponding wrapper class in Java.
| Primitive Type | Wrapper Class |
|---|---|
byte |
Byte |
short |
Short |
int |
Integer |
long |
Long |
float |
Float |
double |
Double |
char |
Character |
boolean |
Boolean |
For example, the primitive int stores a numerical value directly, whereas the Integer class represents that same value as an object.
int number = 100;
Integer objectNumber = Integer.valueOf(100);
Here, number is a primitive integer, while objectNumber is an Integer object.
2. Why Wrapper Classes Are Needed
One of the major reasons wrapper classes are important is that Java's collection framework works with objects rather than primitive data types.
For example, you cannot directly create an ArrayList of primitive int values:
// Not allowed
ArrayList<int> numbers;
Instead, you use the Integer wrapper class:
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
The ArrayList stores Integer objects rather than primitive int values.
Wrapper classes are also useful when a value needs to represent null. A primitive cannot contain null.
Integer age = null;
This is valid because Integer is an object. In contrast:
int age = null;
is invalid because primitive types cannot store null.
3. Creating Wrapper Objects
Wrapper objects can be created using methods such as valueOf().
Integer number = Integer.valueOf(25);
Double price = Double.valueOf(99.50);
Boolean status = Boolean.valueOf(true);
Character letter = Character.valueOf('A');
The valueOf() method returns an object representing the specified primitive value.
In modern Java, explicit creation using constructors such as new Integer(25) should not be used. The constructor-based approach has been deprecated, and valueOf() is preferred.
4. Converting Strings into Wrapper Values
Wrapper classes provide useful methods for converting strings into primitive values.
For example, Integer.parseInt() converts a string into an int.
String value = "500";
int number = Integer.parseInt(value);
System.out.println(number);
Output:
500
Similarly, other wrapper classes provide parsing methods:
double price = Double.parseDouble("125.75");
long population = Long.parseLong("500000");
float percentage = Float.parseFloat("87.5");
boolean result = Boolean.parseBoolean("true");
This is particularly useful when data is received as text but needs to be processed as a numerical or logical value.
5. Converting Primitive Values into Wrapper Objects
The valueOf() method can convert primitive values into wrapper objects.
int value = 50;
Integer number = Integer.valueOf(value);
System.out.println(number);
The primitive int value is represented by an Integer object.
Java also provides automatic conversion between primitives and their wrapper classes through autoboxing and unboxing. These conversions are closely related to wrapper classes and make them easier to use in normal Java programs.
6. Useful Methods of Wrapper Classes
Wrapper classes contain many useful methods for examining and converting values.
For example, the Integer class provides methods such as:
Integer.parseInt("100");
Integer.valueOf(100);
Integer.toBinaryString(10);
Integer.toHexString(255);
Integer.compare(20, 30);
The Character class provides methods for checking and working with characters:
Character.isLetter('A');
Character.isDigit('5');
Character.isUpperCase('A');
Character.isLowerCase('a');
Character.toUpperCase('b');
For example:
char ch = '7';
if (Character.isDigit(ch)) {
System.out.println("The character is a digit");
}
Output:
The character is a digit
These methods are useful when validating or processing input.
7. Wrapper Classes Are Immutable
Wrapper objects are immutable. This means that once a wrapper object has been created, its value cannot be changed.
Consider:
Integer number = 100;
number = 200;
It may appear that the Integer object has changed from 100 to 200, but that is not what happens internally. A new Integer value is assigned to the reference.
This immutability makes wrapper objects safe to use in many situations where objects should not be modified after creation.
8. Wrapper Classes and Collections
Wrapper classes are particularly important when working with Java collections.
For example:
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
for (Integer number : numbers) {
System.out.println(number);
}
Here, Integer allows numerical values to be stored in an ArrayList.
Wrapper classes are also commonly used with other collections:
HashSet<Double> prices = new HashSet<>();
HashMap<String, Integer> marks = new HashMap<>();
In the HashMap example, String is the key type and Integer is the value type.
9. Wrapper Classes and Null Values
Another important advantage of wrapper classes is their ability to represent the absence of a value.
For example:
Integer marks = null;
This can be useful in applications where a value may not yet be available.
For instance:
Integer studentMarks = null;
if (studentMarks == null) {
System.out.println("Marks are not available");
}
Primitive types cannot provide this distinction because they always contain a value.
For example, an int variable might contain 0, but 0 could mean either an actual score of zero or an uninitialized/default value. An Integer can explicitly use null to indicate that no value is available.
10. Wrapper Classes and Comparison
Wrapper objects should be compared carefully. The == operator compares object references in many situations rather than simply comparing the numerical values.
For example:
Integer a = 100;
Integer b = 100;
System.out.println(a.equals(b));
Output:
true
The equals() method compares the values represented by the objects.
For numerical wrapper objects, methods such as compareTo() can also be used:
Integer a = 50;
Integer b = 75;
System.out.println(a.compareTo(b));
Since 50 is smaller than 75, the result is negative.
For general object-value comparison, equals() is usually more appropriate than relying on ==.
11. Common Wrapper Classes in Practical Applications
Integer is frequently used for whole numbers in collections and application data. Double and Float are useful when working with decimal values. Long is suitable for large integer values, such as identifiers or large counts. Boolean represents true or false states, while Character provides methods for processing individual characters.
For example:
Integer age = 25;
Double salary = 45000.75;
Boolean employed = true;
Character grade = 'A';
These variables are objects rather than primitive values and therefore can be used wherever Java expects object types.
12. Example Program
The following program demonstrates several wrapper-class features:
import java.util.ArrayList;
public class WrapperExample {
public static void main(String[] args) {
int value = 100;
Integer number = Integer.valueOf(value);
String text = "250";
int convertedValue = Integer.parseInt(text);
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(number);
numbers.add(convertedValue);
numbers.add(300);
System.out.println("Wrapper object: " + number);
System.out.println("Converted value: " + convertedValue);
System.out.println("Numbers:");
for (Integer n : numbers) {
System.out.println(n);
}
System.out.println("Is 100 an integer? " +
number.getClass().getSimpleName());
}
}
Output:
Wrapper object: 100
Converted value: 250
Numbers:
100
250
300
Is 100 an integer? Integer
13. Advantages of Wrapper Classes
Wrapper classes provide several important benefits in Java:
-
They allow primitive values to be represented as objects.
-
They make primitive values usable with collection classes such as
ArrayListandHashMap. -
They provide useful conversion and utility methods.
-
They can represent
null, unlike primitive data types. -
They support automatic conversion between primitives and objects through autoboxing and unboxing.
-
They provide methods for parsing strings and checking values.
-
They are immutable, which makes their values predictable once created.
Conclusion
Wrapper classes form an important bridge between Java's primitive data types and its object-oriented features. Classes such as Integer, Double, Character, and Boolean allow primitive values to be handled as objects. They are especially important when working with collections, generic types, string conversion, nullable values, and utility methods. Understanding wrapper classes also provides the foundation for understanding autoboxing and unboxing, where Java automatically converts between primitive values and their corresponding wrapper objects.