Wrapper Class in Java – Implement Autoboxing and Unboxing with Examples

Free Java courses with 37 real-time projects - Learn Java

In programs, you must have come across terms like “Integer.parseInt()” and Character.getNumericValue(). Well, these are wrapper classes and simply help to convert primitive data types into Objects. Why objects? Because we need to modify datatypes during programming and objects are useful for doing manipulations. We will also learn about how primitive data types are converted to Wrapper Classes and so on. Let us start!

Wrapper Class in Java

Wrapper Class in Java

Wrapper classes, as the name suggests, wraps around or encapsulates primitive datatypes in Java. We talked about this in one of our previous articles so be sure to check them out too.

Wrapper classes, simply put, is basically a class for converting a primitive datatype, to an object for specific functions. This is useful because primitive datatypes are generally immutable. Also, in Java, everything is object-oriented in nature. So if you want to have a deeper understanding of how this work, read along.

Some of the main reasons why wrapper classes are essential in programming are as follows:

  1. When we are working with methods, it is essential that the arguments we pass to them are objects and not primitive values. Hence wrapper classes help by converting the primitive datatype into its specific Wrapper class.
  2. All classes in java.util package work with objects. Hence if we need to use these classes we need to convert primitive data types to Wrapper class objects.
  3. All collections, such as ArrayLists and Queues work with Objects as input. It is easy if the objects are of a user-defined datatype. But if they are primitive datatypes they cannot directly be stored in the collection. Hence we need to box them into objects and then use them accordingly.
  4. Objects are essential for supporting synchronization in multithreading.
  5. If we want to implement serialization in Java, we can only do so with the help of objects. That is why primitive data types need to be converted to objects.

Table of java Wrapper Classes with their Respective Primitive Classes

Primitive DatatypesWrapper Classes
byteByte
booleanBoolean
charCharacter
int Integer
longLong
shortShort
doubleDouble
floatFloat

Autoboxing in Java

Autoboxing is the process of converting a primitive datatype to its corresponding Wrapper class. You should know that this process is automatic and takes place whenever a method gets a primitive datatype as its argument where it expects an object. This may sound complex at first but trust me, it will get very easy to understand if you look at some of the examples.

If you have seen lists, you must know about ArrayLists in Java. So the ArrayLists take an object as an input to its add() function. The syntax is:

<list_name>.add(<Object of type of ArrayList>)

Now, whenever you add an integer element to a list, it automatically converts it to a respective Integer wrapper class. The object can then prove to be fruitful to the function.

Java Program to Illustrate Autoboxing

package com.dataflair.wrapperclass;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.TypeInfo;

public class Autoboxing {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        int a=3;
        //System.out.println(a.getClass()); This will result in an error because int is not an object.
        list.add(3);// Here the value 3 is primitive but converted to Wrapper class Integer
        list.add(4);
        System.out.println(list.get(0).getClass());
        System.out.println(list.toString());
    }
}

Output

class java.lang.Integer
[3, 4]

Do remove the comment at line 10 and see what error arises for yourself.

Unboxing in Java

Unboxing is the inverse of Autoboxing. It is the process of converting a Wrapper class object into its corresponding Primitive Datatype. For instance, an Integer object would be converted to a primitive data type, i.e, int.

Java Program to Illustrate Unboxing in Java

package com.dataflair.wrapperclass; 
public class Unboxing {
    public static void main(String[] args) {
        
        Integer wrapperInteger = new Integer(4);
        wrapperInteger.getClass();
        int a=wrapperInteger;//Unboxing

        System.out.println(a);
        //a.getClass(); This would result in an error because it is a primitive datatype. 
        
    }
    
}

Output

4

Custom Wrapper Classes in Java

Right now, you may be thinking, “Can I have my own Wrapper Class in Java?” and the answer is yes. You can. In java, you can create custom wrapper classes for yourself. However, this is similar to declaring a class for a datatype. Let us look at an example below.

Program to Illustrate the use of Custom Wrappers in Java

package com.dataflair.wrapperclass;
public class CustomWrapper {

    int i;

    CustomWrapper()
    {
        System.out.println("This is a custom wrapper class");
    }
    CustomWrapper(int num)
    {
        this();
        this.i=num;
        
    }    
    public int getI() {
        return i;
    }


    public static void main(String[] args) {
        
        CustomWrapper custom=new CustomWrapper(54);
        System.out.println(custom.getClass());
    }
}

Output

This is a custom wrapper class
class CustomWrapper

As you can see, this is very easy to understand and grasp. More practice will give you a deeper understanding of Wrapper classes in java.

Advantages of Wrapper Classes

  1. The primary advantage of Wrapper Classes is that we need Wrapper objects to function with collections which is only possible with the help of Wrapper classes.
  2. As the wrapper classes have objects we can store null as a value. We could not store null in variables of primitive datatype.

One important point to note is that primitive datatypes are more efficient than wrapper class objects and it is essential to know when to use which.

Quiz on Wrapper Class in Java

Summary

In Java, wrapper classes form the base of all method invocations. It also allows Java to manipulate primitive data types without changing their actual values. A strong concept of these topics would surely benefit you a lot in your development journey.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

follow dataflair on YouTube

1 Response

  1. Givemore Matengambiri says:

    this is beautifull

Leave a Reply

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