Wrapper Class in Java
What is Wrapper Class?
- As we know, Java is not a pure Object Oriented Language because it uses primitive data types. So Java provides Wrapper classes to convert primitive types to pure Object types.
- Wrapper classes are predefined classes to wrap primitive data types as Object types.
- Wrapper class can hold only its respective primitive data type value.
- Wrapper classes are used in Collection Framework, Hibernate Framework and Spring Framework etc., because collections work only with objects.
- There are 8 Wrapper Classes for 8 primitive types:
Types of Wrapper Classes
| Primitive Type | Wrapper Type |
|---|---|
| byte | Byte |
| short | Short |
| char | Character |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| boolean | Boolean |
What is Autoboxing and Unboxing?
In Java 5, a new feature was introduced called Autoboxing and Unboxing.
Autoboxing
When you wrap primitive data type to its respective Wrapper class, that process is called Autoboxing. Conversion is automatic.
Example:
int i = 10; // primitive
Integer j = i; // Autoboxing - primitive to object automatically
// Internally: Integer j = Integer.valueOf(i);
Unboxing
When you convert Wrapper object to its respective primitive data type, that process is called Unboxing.
Example:
Integer i = 10; // Wrapper object
int j = i; // Unboxing - object to primitive automatically
// Internally: int j = i.intValue();
Conclusion
Wrapper classes make Java more object-oriented. They are essential for Collections (ArrayList, HashMap), Frameworks (Hibernate, Spring), and provide useful utility methods like Integer.parseInt(), valueOf() etc. Use autoboxing/unboxing to simplify code since Java 5.
Next: Parsing, Type Conversion, Wrapper Class Methods
2 comments:
Thanks for all your code and new technology
thank you so much for this sir
Post a Comment