Wrapper Classes in Java: Concept and Usage

Introduction to Wrapper Classes in Java

Java provides wrapper classes to convert primitive data types into objects. These classes are part of the java.lang package and offer various utility methods for type conversion, data manipulation, and object-oriented programming.

What Are Wrapper Classes in Java?

Wrapper classes in Java are used to encapsulate primitive data types within objects. Each primitive type has a corresponding wrapper class:

Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

Importance of Wrapper Classes

  • Object Representation: Converts primitive types into objects.
  • Collection Framework Support: Used in Java Collections like ArrayList and HashMap.
  • Utility Methods: Provides methods for parsing, conversion, and comparisons.
  • Null Handling: Unlike primitive types, wrapper classes can store null values.

Java Primitive to Object Conversion

Using Wrapper Class Constructors (Deprecated in Java 9)

Before Java 9, wrapper classes had constructors to convert primitives into objects:

Integer obj = new Integer(10); // Deprecated

Using valueOf() Method

Instead of constructors, Java recommends using valueOf() for object creation:

Integer obj = Integer.valueOf(10);

Java Wrapper Class Methods

Wrapper classes provide several utility methods for type conversion and manipulation.

Commonly Used Methods

Method Description
parseInt(String s) Converts a string to an int
valueOf(String s) Converts a string to an object
toString() Converts an object to a string
doubleValue() Returns the double equivalent
intValue() Returns the integer equivalent
compareTo(T obj) Compares two objects

Example:

String number = "100"; int result = Integer.parseInt(number); System.out.println(result); // Output: 100

Autoboxing and Unboxing in Java

What is Autoboxing in Java?

Autoboxing is the automatic conversion of a primitive type into its corresponding wrapper class.

int num = 50; Integer obj = num; // Autoboxing

What is Unboxing in Java?

Unboxing is the reverse process, where an object is converted back to a primitive type.

Integer obj = 100; int num = obj; // Unboxing

Why is Autoboxing and Unboxing Important?

  • Reduces Boilerplate Code: No need for explicit conversion.
  • Seamless Integration with Collections: Java collections work with objects, not primitives.
  • Enhances Readability: Cleaner and more intuitive code.

Performance Considerations of Wrapper Classes

  • Memory Overhead: Wrapper objects take more space than primitives.
  • Garbage Collection: Frequent boxing/unboxing can impact performance.
line

Copyrights © 2024 letsupdateskills All rights reserved