Define Wrapper Classes in Java.
In Java, wrapper classes are special classes that allow primitive data types to be treated as objects. Each of the eight primitive data types in Java has a corresponding wrapper class. This is particularly useful when working with collections, such as ArrayList
, which can only store objects and not primitive types.
Here are the eight primitive data types and their corresponding wrapper classes:
Integer
Boolean
Character
Byte
Short
Long
Float
Double
Object Representation: Wrapper classes allow primitive types to be treated as objects. This is useful in situations where an object is required, such as in collections.
Utility Methods: Wrapper classes provide utility methods for converting between types, parsing strings to primitive types, and other operations. For example, Integer.parseInt("123")
converts a string to an int
.
Immutability: Instances of wrapper classes are immutable, meaning that once an object is created, its value cannot be changed. This is similar to String
objects in Java.
Autoboxing and Unboxing: Java provides a feature called autoboxing, which automatically converts a primitive type to its corresponding wrapper class when an object is needed. Conversely, unboxing is the automatic conversion of a wrapper class back to its corresponding primitive type. For example:
int primitive = 5;
Integer wrapper = primitive; // Autoboxing
int backToPrimitive = wrapper; // Unboxing
Null Values: Wrapper classes can hold a null
value, which is not possible with primitive types. This can be useful in scenarios where you need to represent the absence of a value.
Here’s a simple example demonstrating the use of wrapper classes:
import java.util.ArrayList;
public class WrapperClassExample {
public static void main(String[] args) {
// Using wrapper classes with ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10); // Autoboxing
numbers.add(20);
// Accessing elements (unboxing)
for (Integer number : numbers) {
System.out.println(number); // Prints 10 and 20
}
// Using a wrapper class method
String str = "123";
int num = Integer.parseInt(str); // Parsing string to int
System.out.println(num); // Prints 123
}
}
In summary, wrapper classes in Java provide a way to use primitive data types as objects, enabling more flexibility and functionality in programming, especially when working with collections and APIs that require objects.