Autoboxing and Unboxing in Java- When and how to do it?

In this java tutorial, we are going to learn autoboxing and unboxing in Java. We have briefly discussed this topic in our tutorial of Java wrapper classes. Java introduced the concept of Autoboxing and Unboxing since Java 5.

Using this concept we can interchangeably convert the primitive data types into their respective wrapper classes.

Let’s start discussing what is autoboxing and unboxing in Java.

What is Autoboxing and Unboxing in Java

Autoboxing

Autoboxing in Java is a process of converting a primitive data type into an object of its corresponding wrapper class. For example, converting int to Integer class, long to Long class or double to Double class, etc.

When Autoboxing in Java occurs?

The Java compiler applies autoboxing under three cases:

Case 1

When we pass a primitive data type as a parameter to a method but that method expects an object of the wrapper class related to that primitive data type.

Code to explain this case:

package com.techvidvan.autoboxing;
public class Example1
{
    public static void myMethod(Integer num)
    {
        System.out.println(num);
    }
    public static void main(String[] args)
    {
        //passed int (primitive type), but compiler automatically converts it to the Integer object.
        myMethod(5);
    }
}

Output:

5
Case 2

When we assign a primitive data type to a variable of its corresponding wrapper class.

Code to explain this case:

package com.techvidvan.autoboxing;
public class Example2
{
    public static void main(String[] args)
    {
        Integer inum = 3; //Assigning int to Integer: Autoboxing
        Long lnum = 32L; //Assigning long to Long: Autoboxing
        System.out.println(inum);
        System.out.println(lnum);   
    }
}

Output:

3
32
Case 3

When we work with collection framework classes, the compiler performs autoboxing in java.

For example, the framework ArrayList class expects an object of Integer wrapper class but we are passing the int primitive data type, so here compiler will automatically convert the int data type into the object of Integer wrapper class.

Code to explain this case:

package com.techvidvan.autoboxing;
import java.util.ArrayList;
public class Example3
{
    public static void main(String[] args)
    {
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        //Autoboxing: int primitive to Integer
        arrayList.add(11);
        arrayList.add(22);
        System.out.println(arrayList);
    }
}

Output:

[11, 22]

Unboxing

Unboxing in Java is an automatic conversion of an object of a wrapper class to the value of its respective primitive data type by the compiler.

It is the opposite technique of Autoboxing. For example converting  Integer class to int datatype, converting Double class into double data type, etc.

When Unboxing in Java occurs?

The Java compiler applies unboxing under three cases:

Case 1

When we pass an object of a wrapper class as a parameter to a method but that method expects a value of the corresponding primitive type.

Code to explain this case:

package com.techvidvan.unboxing;
public class Example1
{
    public static void myMethod(int num)
    {
        System.out.println(num);
    }
    public static void main(String[] args)
    {
        Integer intObject = new Integer(100);
        // passed Integer wrapper class object, would be converted to int primitive type
        myMethod(intObject );
    }
}

Output:

100
Case 2

When we assign an object of the wrapper class to its respective primitive datatype.

Code to explain this case:

package com.techvidvan.unboxing;
public class Example2
{   
    public static void main(String[] args)
    {
        Integer intObject = new Integer(5);
        int num = intObject; //unboxing object to primitive type
        System.out.println(num);
    }
}

Output:

5
Case 3

While dealing with collection classes.

Code to explain this case:

package com.techvidvan.unboxing;
import java.util.ArrayList;
public class Example1
{   
    public static void main(String[] args)
    {
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        arrayList.add(10);
        int num = (int) arrayList.get(0);
// unboxing because get method returns an Integer object
        System.out.println(num);
    }
}

Output:

10

Advantage of Autoboxing and Unboxing in Java

A Java programmer does not need to explicitly or manually write the code to convert primitive data to the wrapper class object and vice versa. Java compiler automatically performs autoboxing and unboxing as and when needed.

List of primitive data types and their respective wrapper classes

The following table shows the  primitive types and their corresponding wrapper classes, which the Java compiler uses to perform Autoboxing and Unboxing:

Different Examples of Autoboxing and Unboxing
Example 1
package com.techvidvan.conversion;
public class TechVidvan
{
    public static void main (String[] args)
    {
        // creating an Integer Object with value 10.
        Integer intObject = new Integer(10);

        // unboxing the Object
        int intDataType = intObject;

        System.out.println("Value of object of Character class: " + intObject);
        System.out.println("Value of char data type: " + intDataType);

        //Autoboxing of char
        Character charObject = 'a';

        // Auto-unboxing of Character
        char charDataType = charObject;

        System.out.println("Value of object of Integer class: " + charDataType);
        System.out.println("Value of int data type: " + charObject);
    }
}

Output:

Value of object of Character class: 10
Value of char data type: 10
Value of object of Integer class: a
Value of int data type: a
Example 2
package com.techvidvan.conversion;
import java.util.ArrayList;
public class TechVidvan
{
    public static void main (String[] args)
    {
//Creating a list of elements of Integer type and adding the int type values        ArrayList<Integer> list = new ArrayList<Integer>();
  
      for (int i = 0; i < 10; i++)
            list.add(i);
            System.out.println(list);
    }
} 

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 3:

package com.techvidvan.conversion;
import java.io.*;
import java.util.*;
public class TechVidvan
{
    // Java program find sum of first 10 numbers using autoboxing and unboxing

    public static int sumOfNumbers(List<Integer> list)
    {
        int sum = 0;
        for (Integer num : list)
        {
            // unboxing of i automatically
            sum += num;
            //unboxing of num is done automatically using intvalue implicitly
        }
        return sum;
    }

    public static void main (String[] args)
    {
/* Creating a list Integer type elements and adding the int values to the list*/

        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 10; i++)
            list.add(i);

        // getting the sum of all odd no. in the list.
        int sum = sumOfNumbers(list);
        System.out.println("Sum of first 10 numbers is = " + sum);
    }
}

Output:

Sum of first 10 numbers is = 45

Things to Remember while using Autoboxing and Unboxing in Java

Till now we discussed what Autoboxing and Unboxing are in Java and the cases when it occurs. But there are some precautions that you need to take care of while using Autoboxing and Unboxing in Java. Let’s discuss these cases:

1. Comparing Objects with equality Operator

There are few situations where java autoboxing is error-prone for example,  when using the equality operator “==”. Since we can use the equality operator both primitive types as well as objects it may lead to confusion.

Generally, the best practice is to use the equality operator with primitive types rather than objects. In the case of the object, we should use the equals method.

2. Mixing object and primitive type with equality and relational operator

The next thing that you should remember while using Autoboxing is that you should not mix the primitive types and Object with equality or relational operator.

If you try to compare a primitive type with an object then there could be a NullPointerException if the object is null. For example:

private static Integer number;
//NullPointerException on unboxing
if( number <= 0)
{
        System.out.println("Number is invalid");
}
3. Cached Objects

Another risk while using Autoboxing and Unboxing is a cached object. The valueOf() method creates the boxed primitive type and it caches frequently used Object.

4. Unnecessary objects and GC overhead

The last problem with Autoboxing and unboxing is the expenses related to them. As the technique of autoboxing creates an unnecessary object, it can potentially slow down the speed of your program by frequent garbage collection.

Conclusion

Autoboxing and unboxing in java are automatically done by the Java compiler. In this Java article, we learned Java autoboxing and unboxing. We discussed the advantages of Autoboxing in java and Unboxing in java.

We also discussed some situations and examples where autoboxing and unboxing come into the picture.

Thank you for reading our article. Do share your feedback through the comment section below.

Happy Learning 🙂