In Java, a wrapper class is a class that wraps (encapsulates) primitive data types within an object.
The purpose of wrapper classes is to provide a way to treat primitive data types as objects.
The Java platform provides a set of built-in wrapper classes for each primitive data type:
Byte: Wraps a byte value.
Short: Wraps a short value.
Integer: Wraps an int value.
Long: Wraps a long value.
Float: Wraps a float value.
Double: Wraps a double value.
Character: Wraps a char value.
Boolean: Wraps a boolean value.
Wrapper classes are particularly useful when we need to work with collections (such as ArrayList or HashMap) that can only store objects, not primitive types.
They are also commonly used in APIs that require objects rather than primitive types.
Wrapper classes provide methods to convert between primitive types and objects, as well as to perform various operations on the wrapped values.
Integer wrapper class example.
public class WrapperClassesExample { public static void main(String[] args) { // Creating wrapper objects Integer intWrapper = new Integer(10); // Accessing values and performing operations int intValue = intWrapper.intValue(); // Printing values System.out.println("Integer value: " + intValue); // Output: Integer value: 10 // Using static methods for conversion int parsedInt = Integer.parseInt("123"); System.out.println("Parsed int: " + parsedInt); // Output: Parsed int: 123 } }
public class WrapperClassesExample { public static void main(String[] args) { // Creating wrapper objects Double doubleWrapper = new Double(3.14); // Accessing values and performing operations double doubleValue = doubleWrapper.doubleValue(); // Printing values System.out.println("Double value: " + doubleValue); // Output: Double value: 3.14 // Using static methods for conversion double parsedDouble = Double.parseDouble("3.14"); System.out.println("Parsed double: " + parsedDouble); // Output: Parsed double: 3.14 } }
public class WrapperClassesExample { public static void main(String[] args) { // Creating wrapper objects Character charWrapper = new Character('A'); // Accessing values and performing operations char charValue = charWrapper.charValue(); // Printing values System.out.println("Character value: " + charValue); // Output: Character value: A } }
public class WrapperClassesExample { public static void main(String[] args) { // Creating wrapper objects Boolean boolWrapper = new Boolean(true); // Accessing values and performing operations boolean boolValue = boolWrapper.booleanValue(); // Printing values System.out.println("Boolean value: " + boolValue); // Output: Boolean value: true } }
Double wrapper class example.
Character wrapper class example.
Boolean wrapper class example.
In addition to constructors and methods for converting between primitive types and objects, wrapper classes also provide methods for arithmetic operations, comparison, and other utilities.