Wrapper Classes Basics
What are Wrapper Classes?
In Java, wrapper classes provide a way to convert primitive data types into objects. Each primitive type has a corresponding wrapper class that encapsulates the primitive value and offers additional methods for manipulation.
Primitive Types and Their Wrapper Classes
Primitive Type |
Wrapper Class |
int |
Integer |
char |
Character |
boolean |
Boolean |
double |
Double |
float |
Float |
long |
Long |
short |
Short |
byte |
Byte |
Why Use Wrapper Classes?
graph TD
A[Primitive Type] --> B{Need Object Functionality?}
B -->|Yes| C[Use Wrapper Class]
B -->|No| D[Use Primitive Type]
C --> E[Supports Generics]
C --> F[Provides Utility Methods]
C --> G[Allows Null Values]
Key Reasons for Using Wrapper Classes:
- Support for generics
- Utility methods for type conversion
- Ability to store null values
- Integration with Java Collections Framework
Creating Wrapper Objects
// Different ways to create wrapper objects
Integer num1 = new Integer(100); // Deprecated constructor
Integer num2 = Integer.valueOf(100); // Recommended method
Integer num3 = 100; // Autoboxing
// Parsing strings to wrapper objects
Integer parsedNum = Integer.parseInt("123");
Double parsedDouble = Double.parseDouble("3.14");
Autoboxing and Unboxing
Autoboxing automatically converts primitive types to wrapper objects, while unboxing converts wrapper objects back to primitive types.
// Autoboxing
Integer autoBoxedInt = 42;
// Unboxing
int unboxedInt = autoBoxedInt;
Common Wrapper Class Methods
Most wrapper classes provide useful methods for type conversion and manipulation:
parseXXX()
: Convert strings to primitive types
toString()
: Convert to string representation
compareTo()
: Compare wrapper objects
equals()
: Check value equality
Best Practices
- Prefer
valueOf()
over deprecated constructors
- Be aware of memory implications
- Use autoboxing and unboxing judiciously
- Consider performance in performance-critical code
By understanding wrapper classes, you'll enhance your Java programming skills and leverage more advanced language features. LabEx recommends practicing these concepts to gain proficiency.