DEV Community

Cover image for Java Wrapper Class
KIRUBAGARAN .K
KIRUBAGARAN .K

Posted on

Java Wrapper Class

Java Wrapper Classes provide a way to use primitive data types as objects. Java is an object-oriented language. However, it includes primitive data types like int, char, boolean, and double for performance reasons. Wrapper classes solve the need to treat these primitives as objects.

Why Use Wrapper Classes?

Collections Framework
Java collections like ArrayList and HashMap store objects. They cannot directly store primitive types. Wrapper classes allow you to store primitive values in these collections.

Utility Methods:
Wrapper classes provide many useful static utility methods. These methods help convert values, parse strings, and perform other operations on primitive data. For example, Integer.parseInt("123") converts a string to an integer.

Integer num = Integer.parseInt("123"); // String → int
int max = Integer.max(10, 20); // find max

Wrapper objects allow primitives to be used in object-oriented features like methods, synchronization, and serialization.

Primitive data types and their corresponding wrapper class

Autoboxing and Unboxing

Java provides automatic conversion between primitive types and their wrapper class objects. This feature is called autoboxing and unboxing.

Autoboxing

Autoboxing is the automatic conversion of a primitive data type to an object of the corresponding wrapper class.

For example, boolean to Boolean, char to Character, byte to Byte, short to Short, int to Integer, long to Long, float to Float, and double to Double.

int num = 10;
Integer obj = num; // automatically converted

Unboxing

Unboxing is just the reverse process of autoboxing. It is the automatic conversion of a wrapper class object to the corresponding primitive data type.

Integer obj = 20;
int num = obj; // automatically converted

Top comments (0)