Wrapper Classes in Java | Autoboxing vs Unboxing

A Wrapper class is a class whose object wraps or contains a primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store a primitive data types.

Wrapper classes in java provides the mechanism to convert primitive into object and object into primitive.

Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive automatically. The automatic conversion of primitive into object is known as autoboxing and vice-versa unboxing.

The eight classes of java.lang package are known as wrapper classes in java. The list of eight wrapper classes are given below:

Primitive TypeWrapper class
booleanBoolean
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble

 

Autoboxing – 

Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc.

The Java compiler applies autoboxing when a primitive value is:

  • Passed as a parameter to a method that expects an object of the corresponding wrapper class.
  • Assigned to a variable of the corresponding wrapper class.

Run Online

Output
20 20 10
Unboxing – 

It is just the reverse process of autoboxing. Converting an object of a wrapper class to its corresponding primitive type is known as unboxing.

The Java compiler applies unboxing when an object of a wrapper class is:

  • Passed as a parameter to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.

Run Online

Output
Character ch: a
char a: a
Need of Wrapper Classes –
  1. They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value).
  2. The classes in java.util package handles only objects and hence wrapper classes help in this case also.
  3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and not primitive types.
  4. An object is needed to support synchronization in multithreading.
Advantages of Autoboxing / Unboxing –
  • Autoboxing and unboxing lets developers write cleaner code, making it easier to read.
  • The technique let us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly.

Leave a Reply

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