Wrapper class
In Java, a wrapper class provides a mechanism to convert primitive data types into objects and vice versa. Primitive data types like
int, char, float, and boolean are not objects and cannot be used in contexts that require objects, such as Java Collections Framework (e.g., ArrayList, HashMap) or with generics. Wrapper classes address this limitation by "wrapping" the primitive value within an object.Key aspects of wrapper classes in Java:
- Primitive to Object Conversion (Autoboxing): Wrapper classes allow you to convert a primitive value into an object of its corresponding wrapper class. For example, an
intcan be converted to anIntegerobject. Since J2SE 5.0, this conversion happens automatically through a feature called autoboxing.
- Object to Primitive Conversion (Unboxing): Conversely, wrapper classes also allow you to extract the primitive value from a wrapper object. This process is known as unboxing, and it also happens automatically since J2SE 5.0.
- For each of the eight primitive data types in Java, there is a corresponding wrapper class in the
java.langpackage:byte->Byteshort->Shortint->Integerlong->Longfloat->Floatdouble->Doublechar->Characterboolean->Boolean
- Collections: Wrapper classes enable the storage of primitive values in Java Collections, which only store objects.
- Generics: They are essential for using primitive types with generic classes and methods, as generics work with object types.
- Utility Methods: Wrapper classes provide useful static methods for converting between strings and numbers, parsing, and other operations (e.g.,
Integer.parseInt(),Character.isDigit()). - Null Values: Unlike primitives, wrapper class objects can hold a
nullvalue, which can be useful in certain scenarios for representing the absence of a value.
Comments
Post a Comment