what are wrapper classes in Java

What are wrapper classes in Java?

In Java, wrapper classes are classes that allow primitive data types to be treated as objects. They “wrap” the primitive data types and provide utility methods for dealing with them as objects. The Java programming language provides a set of built-in wrapper classes for each of the primitive data types. Here’s a list of primitive data types and their corresponding wrapper classes:

  1. Primitive Data Type: int
    • Wrapper Class: Integer

Example Usage:

Method 1

int primitiveInt = 10;
Integer wrappedInt = new Integer(primitiveInt); // Wrapping
int unwrappedInt = wrappedInt.intValue(); // Unwrapping

Primitive Data Type: double

  • Wrapper Class: Double

Example Usage:

Method 1

double primitiveDouble = 3.14;
Double wrappedDouble = new Double(primitiveDouble); // Wrapping
double unwrappedDouble = wrappedDouble.doubleValue(); // Unwrapping

Primitive Data Type: char

  • Wrapper Class: Character

Example Usage:

Method 1

char primitiveChar = 'A';
Character wrappedChar = new Character(primitiveChar); // Wrapping
char unwrappedChar = wrappedChar.charValue(); // Unwrapping

Primitive Data Type: boolean

  • Wrapper Class: Boolean

Example Usage:

Method 1

boolean primitiveBoolean = true;
Boolean wrappedBoolean = new Boolean(primitiveBoolean); // Wrapping
boolean unwrappedBoolean = wrappedBoolean.booleanValue(); // Unwrapping

Autoboxing and Unboxing:

Java provides a feature called autoboxing and unboxing which allows automatic conversion between primitive types and their corresponding wrapper classes. For example, you can assign a primitive value to a wrapper class without explicitly creating an object (autoboxing), and vice versa (unboxing).

Here’s an example:

Method 1

int primitiveInt = 42;
Integer wrappedInt = primitiveInt; // Autoboxing (primitive to wrapper)
int unwrappedInt = wrappedInt; // Unboxing (wrapper to primitive)

These wrapper classes are particularly useful when you need to use primitive data types in situations that require objects, such as collections (like ArrayLists) and certain APIs that work with objects.

Leave a Reply

Your email address will not be published. Required fields are marked *