Java | Wrapper classes, autoboxing and unboxing

| By Webner

Wrapper classes are the classes to convert the primitive types to objects of their respective class. We have many primitive types in Java like int, float, char etc. These primitive types can not be used in Collections as Collections only allow objects. Therefore in such situations wrapper classes are used. Wrapper classes in Java are Integer for int, Float for float, Double for double etc. A primitive type can be easily converted to the object of these wrapper class and vice versa.

Declaring and initialising primitive type:

int temp=10;

Declaring and initialising object of wrapper class:

Integer temp=new Integer(10);

Where Integer is the wrapper class that wraps the int value 10 and makes it an object.

In Java, Collections allows only objects but we can also pass a primitive value to a collection as it is automatically converted to object by Java Compiler. This process is called autoboxing. Autoboxing is the conversion of primitive types to the object itself to be used as an object in collections or methods.

For Example:

ArrayList arraylist = new ArrayList();

Here in this example, we are passing the int values to the arraylist Collection. Although Collections can contains only objects but it is possible to pass primitive to it. It itself get converted to the object which is then used in Collections.

This automatic conversion of primitive type to the object to be used in collections or in methods accepting only objects as a parameter is called Autoboxing.

Compiler uses valueOf() method to convert primitive to Object and uses intValue(), doubleValue() etc to get primitive value from Object.

For Example:

ArrayList arraylist=new ArrayList();

Is equivalent to

ArrayList arraylist=new ArrayList();

In the same way, we can also convert the object of the wrapper class to the primitive type.

For example:

Integer i=new Integer(29);
int a=i;

In this example as we are creating an object of wrapper class Integer then assigning it to the primitive type. No error occurs as Java compiler automatically convert it to the primitive integer.

This automatic conversion of object to the primitive type is called Unboxing.

Leave a Reply

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