In Java, wrapper classes provide a way to represent primitive data types as objects. This is useful when you need to work with collections, generics, or other situations where objects are required instead of primitives. Here are the wrapper classes for the primitive data types:
Byte
: Represents a byte value.Short
: Represents a short value.Integer
: Represents an int value.Long
: Represents a long value.Float
: Represents a float value.Double
: Represents a double value.Character
: Represents a char value.Boolean
: Represents a boolean value.Here's a basic example of how to use wrapper classes:
public class WrapperExample { public static void main(String[] args) { // Using wrapper classes to create objects Integer intObj = new Integer(10); Double doubleObj = new Double(3.14); Character charObj = new Character('A'); Boolean boolObj = new Boolean(true); // Using autoboxing (automatic conversion from primitive to wrapper) Integer intObjAuto = 20; Double doubleObjAuto = 6.28; Character charObjAuto = 'B'; Boolean boolObjAuto = false; // Using unboxing (automatic conversion from wrapper to primitive) int intValue = intObjAuto; double doubleValue = doubleObjAuto; char charValue = charObjAuto; boolean boolValue = boolObjAuto; // Displaying values System.out.println("Integer value: " + intObj); System.out.println("Double value: " + doubleObj); System.out.println("Character value: " + charObj); System.out.println("Boolean value: " + boolObj); System.out.println("Autoboxed Integer value: " + intObjAuto); System.out.println("Autoboxed Double value: " + doubleObjAuto); System.out.println("Autoboxed Character value: " + charObjAuto); System.out.println("Autoboxed Boolean value: " + boolObjAuto); System.out.println("Unboxed int value: " + intValue); System.out.println("Unboxed double value: " + doubleValue); System.out.println("Unboxed char value: " + charValue); System.out.println("Unboxed boolean value: " + boolValue); } }
In this example, we demonstrate creating wrapper objects using the constructor and using autoboxing and unboxing features introduced in Java 5. Autoboxing allows you to automatically convert primitive types to their corresponding wrapper objects, and unboxing allows you to automatically convert wrapper objects to their corresponding primitive types.