AutoBoxing and Auto-unboxing in Java

Two features that were a part of new features list of JDK5 are Autoboxing and Auto-unboxing.
Autoboxing is the process of automatically encapsulating a primitive data type into an object.
Auto-unboxing refers to the process of automatically extracting the value from the type wrapper without the use of functions such as intValue() or charValue().

We can simply use the following code to create an object of the primitive data type:

Integer iOb = 5; //autoboxing int
Character chOb = 'A'; //autoboxing char
Double dOb = 3.14; //autoboxing double

We do not need to use the new keyword to create an object. It is automatically done by Java, thus Autoboxing Similarly, Auto-unboxing can be simply done by the following way:

int i = iOb; //auto-unboxing the int type
char ch = chOb; //auto-unboxing the char type
double d = dOb; //auto-unboxing the double type

Using Expressions to Autobox and Auto-unbox

The best example of Autoboxing and Auto-unboxing is when we are using expressions which deal with primitive types. In an expression, a numeric type is automatically unboxed, the operation is performed and then the object is automatically boxed into an object again. The following example shows this:

/**
 * The following program shows the use of objects in expressions
 * thus demonstrating Autoboxing and Auto-unboxing
 */

public class AutoboxExpDemo {

    public static void main(String args[]) {
        Integer iOb = 56;
        System.out.println("Value of iOb = " + iOb);

        //In the statement iOb++, the object iOb is first auto-unboxed to
        // extract the value and perform the increment operation
        // and then it is autoboxed again
        iOb++;
        System.out.println("Value of iOb++ = " + iOb);

        //Similar to the above operation, in this case iOb is again unboxed
        //to operate on the value and then it is boxed again
        iOb = iOb * (iOb + 3);
        System.out.println("Final Value of iOb = " + iOb);
    }
}

Output:-
Value of iOb = 56
Value of iOb++ = 57
Final Value of iOb = 3420

Using Methods to Autobox and Auto-unbox

Auto-unboxing can automatically occur when an object needs to be converted into its primitive type, eg: when returning an object if the return type is a primitive type and if an object that is passed as an argument is returned. Also, if any method returns a primitive data type and that return value is assigned to an object then Java automatically boxes it into an object. The following example shows Autoboxing and Auto-unboxing in methods:

/**
 * The following program shows autoboxing and auto-unboxing in methods.
 * This program takes a number and displays its reverse
 */

import java.util.Scanner;

public class AutoboxMethodDemo {
    static int rev(Integer iOb) {
        int d, r = 0;

        //Auto-unboxing occurs when the object is being operated on.
        while (iOb != 0) {
            d = iOb % 10;
            r = r * 10 + d;
            iOb = iOb / 10;
        }
        return r;
    }

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number : ");
        int i = in.nextInt();

        //The int type i is being autoboxed into Integer. Also the returned value is again autoboxed into integer
        Integer iOb = rev(i);
        System.out.println("The reverse of the number is : " + iOb);
    }
}

Output:-
Enter a number : 
123
The reverse of the number is : 321

Objects to control Switch statements and if-else statements

The Integer objects can be used to control the switch statement easily with the help of Auto-unboxing. The object is passed as the switch condition and the compiler automatically unboxes the object to extract the int data which is then used as the condition. An example is shown below:

/**
 * The following program shows the use of objects as condition to a switch statement.
 * It takes the user's choice and displays the days of the week
 */

import java.util.Scanner;

public class AutoboxSwitchDemo {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        Integer iOb; //declaring an Integer object

        System.out.println("Enter the serial number of the day you wish to see : ");
        iOb = in.nextInt(); //autoboxing the int value into the Integer object iOb

        //The switch statement automatically unboxes the Integer object iOb and extracts the int value
        switch (iOb) {
            case 1:
                System.out.println("Sunday");
                break;
            case 2:
                System.out.println("Monday");
                break;
            case 3:
                System.out.println("Tuesday");
                break;
            case 4:
                System.out.println("Wednesday");
                break;
            case 5:
                System.out.println("Thursday");
                break;
            case 6:
                System.out.println("Friday");
                break;
            case 7:
                System.out.println("Saturday");
                break;
            default:
                System.out.println("Wrong choice");
        }
    }
}

Output:-
Enter the serial number of the day you wish to see : 
4
Wednesday

We know that if takes boolean as the control type. With the help of Auto-unboxing, it is possible to pass a Boolean object in the place of the condition to make the if statement work. This is shown below:

/**
 * The following program shows the use of objects as condition to an if statement
 */

public class AutoboxIfDemo {
    public static void main(String args[]) {
        Boolean bOb = true; //creating Boolean object with value true

        //If statement auto-unboxes the Boolean object bOb to extract
        // the value true and take it as a condition
        if (bOb) {
            System.out.println("bOb contains True");
        } else {
            System.out.println("bOb contains False");
        }
    }
}

Output:-
bOb contains True

Mixed Type expressions using objects

While performing operations on objects it is completely valid to perform operations between mixed type data as a programmer would have done with normal primitives. The objects are automatically unboxed, operations are performed and then the objects are automatically boxed into objects again. An example is shown below:

/**
 * The following program shows the use of objects in mixed
 * expressions thus demonstrating Autoboxing and Auto-unboxing
 */

public class AutoboxMixExpDemo {
    public static void main(String args[]) {
        //creating Integer object with value 56
        Integer iOb = 66;
        //creating Double object with value 30.0
        Double dOb = 30.0;
        System.out.println("Value of iOb = " + iOb);
        System.out.println("Value of dOb = " + dOb);

        //Operating on Integer and Double objects which are first unboxed
        //to perform the operation and then the value is boxed and stored into dOb
        dOb = iOb / dOb;
        System.out.println("Final Value of dOb = " + dOb);

    }
}

Output:-
Value of iOb = 66
Value of dOb = 30.0
Final Value of dOb = 2.2

Advantages of Autoboxing and Auto-unboxing

  • Autoboxing and Auto-unboxing removes the user’s need to manually construct an object to wrap a primitive data type
  • It is important when implementing the concepts of generics and collection framework. It is because we can not use a primitive type in Collections or Generics because for Example HashMap<Integer, Integer> is valid and not  HashMap<int, int>.
  • It helps to prevent errors.
  • It makes the coding of many algorithms well organized.

Note: Although Autoboxing and Auto-unboxing make dealing with the objects as simple as dealing with actual primitives, it should be kept in mind that objects should be used only where it is required. Using objects in place of primitives can add overhead which should be avoided.

Learning never exhausts the mind.So, do come back for more. Hope this helps and you like the tutorial. Do ask for any queries in the comment box and provide your valuable feedback. Share and subscribe.

Keep Coding!! Happy Coding!! 🙂