Wrapped classes are classes that allow primitive types to be accessed as objects.
In Core Java, wrapped classes refer to classes that encapsulate primitive data types within objects. The primary purpose of wrapped classes is to provide a way to use primitive data types as objects. This is often necessary in situations where objects are required, such as when working with data structures or collections that can only store objects.
The following are the commonly used wrapped classes in Java:
- Integer: Wraps an int.
- Double: Wraps a double.
- Float: Wraps a float.
- Character: Wraps a char.
- Boolean: Wraps a boolean.
- Byte: Wraps a byte.
- Short: Wraps a short.
- Long: Wraps a long.
For example, instead of using a primitive int
, you can use the Integer
class:
int primitiveInt = 42;
Integer wrappedInt = new Integer(primitiveInt);
Starting from Java 5, autoboxing and unboxing were introduced, allowing automatic conversion between primitive types and their corresponding wrapper classes:
int primitiveInt = 42;
Integer wrappedInt = primitiveInt; // Autoboxing
int newPrimitiveInt = wrappedInt; // Unboxing
Autoboxing automatically converts a primitive type to its corresponding wrapper class, and unboxing automatically converts a wrapper class object to its primitive type. These features simplify the code and make it more readable.