What is Autoboxing and Unboxing in Java with Example Program

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

In this Java tutorial, we will learn about autoboxing in java and unboxing in java. So let’s start!!!!

Autoboxing in Java

Autoboxing is the process of converting a primitive data type to a Wrapper class object automatically by the compiler.

Here the compiler checks whether the method expects an object where it was passed a parameter. Then it automatically converts the required primitive data type to a Wrapper class object.

Why do we need this at all? Well, this boils down to the fact that we need some special methods to be performed on datatypes which are primitive in nature.

This, in turn, results in us having classes namely wrapper classes.

These in turn result in the need for conversion of primitive data types to and from wrapper classes.

Now programmers do have a lot on their minds so they do not want to be bothered by these kinds of methods. This is where the Java compiler comes in to the rescue.

The Java compiler automatically converts the primitive data types to their respective Wrapper class objects.

For example, int becomes Integer, float becomes Float, double becomes Double and so on…

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

Simple right?

Let us make some code!

Java program to illustrate the use of Autoboxing in Java:

package com.dataflair.autoboxunbox;
import java.util.*;

public class AutoBox
{
public static void main(String[] args) {
        //We are going to declare a Stack which can only store Integer values in it. 
        Stack<Integer>stack = new Stack<>();
        int a=6;
        int b=12;
        stack.push(a);
        stack.push(b);
        System.out.println(stack.pop());
        
    }
}

Output:

12

So the main focus of this is to perform a stack operation that could access only Integer elements, as we already see here.

But why didn’t the compiler throw an error even though we specifically asked it to push primitive data types in the stack?

Well, this is because of autoboxing, the compiler automatically converts the primitive datatype to its respective wrapper class in the example above.

Unboxing in Java

Unboxing, as the name suggests, is the complete inverse of autoboxing.

During unboxing the compiler converts the wrapper class object to its respective primitive type.

This essentially means that the compiler basically juggles objects and their respective data types and uses whichever one suits the needs.

Let us take an example, in fact, let us take the same example as above.

package com.dataflair.autoboxunbox;
import java.util.*;

public class Main
{
    public int add(Integer a, Integer b)
{
    return a+b;
    
}
    public static void main(String[] args) {
        //We are going to declare a Stack which can only store Integer values in it. 
        Stack<Integer>stack = new Stack<>();
        int a=6;
        int b=12;
        stack.push(a);
        stack.push(b);
        System.out.println(new Main().add(stack.pop(),stack.pop()));
        
    }
}

Output:

18

So what exactly happened there? How is it so that when we pass two Integer values to the function sum, it does not throw an error while trying to add them, but instead, it adds them and returns an int value as specified in the function as before?

Well, this is the magic of the compiler again. It understands that the program needs to add two numbers of type Integer which is not possible.

Hence it converts these values to the required primitive values and returns an int value instead of an Integer object.

Advantages of Java Autoboxing and Unboxing

  • Developers have one less thing to worry about.
  • Helps in writing cleaner code.
  • Prevents unnecessary typecasting.
  • A null operator is autoboxed/unboxed to null itself.

Autoboxing with Method Overloading in Java

When we plan to use autoboxing and unboxing in unison in Java, there are a few rules that we need to keep in mind before we decide to progress with our programs.

a. Boxing gets lower preference when compared to Widening

When the function overloading gets a parameter that has upper type-casting(widening) involved, the autoboxing is prevented and the widening function gets called.

An example would be

package com.dataflair.autoboxunbox;
public class Main
{
    public static void conv(Float f)
    {
        System.out.println("The value got converted to its wrapper class.");
    }
    public static void conv(float f)
    {
        System.out.println("The value got converted to a wider primitive datatype");
    }
    public static void main(String[] args) {
        int a=9;
        conv(a);
    }
}

Output:

The value got converted to a wider primitive datatype

b. Boxing is preferred over var args

The compiler prefers boxing and unboxing over varargs. Hence it binds the method call to perform boxing.

A simple example would be

package com.dataflair.autoboxunbox;
public class Main
{
    public static void conv(Float f)
    {
        System.out.println("The function with the single parameter got executed");
    }
    public static void conv(Float... f)
    {
        System.out.println("The function with variable arguments got executed");
    }
    public static void main(String[] args) {
        float a=9;
        conv(a);
    }
}

Output:

The function with the single parameter got executed

c. Widening beats varargs

The compiler prefers widening of variables in contrast to varargs. Hence it performs widening instead of taking the parameters as a variable argument.

A simple example would be

package com.dataflair.autoboxunbox;


public class Main
{
    public static void conv(float f)
    {
        System.out.println("The function with widened parameter got executed");
    }
    public static void conv(Float... f)
    {
        System.out.println("The function with variable arguments got executed");
    }
    public static void main(String[] args) {
        int a=9;
        conv(a);
    }
}

Output:

The function with widened parameter got executed

Quiz on Autoboxing and Unboxing in Java

Summary

Hence in this article we came to know about Autoboxing and Unboxing in Java.

This is a very important concept to know because this can help developers in debugging special programs where the type of the variable or an object is key.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

follow dataflair on YouTube

2 Responses

  1. Smita Gautam says:

    nice content…really useful

Leave a Reply

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