Explain autoboxing and unboxing in Java with an example

Auto-boxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called un-boxing.

Here is the simplest example of auto-boxing:

char ch = 'a';

Consider the following code:

List <Integer> intList = new ArrayList <> ();
for (int i = 1; i < 50; i += 2)
    intList.add(i);

Although you add the int values as primitive types, rather than Integer objects, to intList, the code compiles. Because intList is a list of Integer objects, not a list of int values, you may wonder why the Java compiler does not issue a compile-time error. The compiler does not generate an error because it creates an Integer object from i and adds the object to intList. Thus, the compiler converts the previous code to the following at runtime:

List <Integer> intList = new ArrayList <> ();
for (int i = 1; i < 50; i += 2)
    intList.add(Integer.valueOf(i));

Converting a primitive value (an int, for example) into an object of the corresponding wrapper class (Integer) is called autoboxing. The Java compiler applies autoboxing when a primitive value is:

  • Passed as a parameter to a method that expects an object of the corresponding wrapper class.
  • Assigned to a variable of the corresponding wrapper class.Consider the following method:
public static int sumEvenInteger(List <Integer> intList) {
    int sum = 0;
    for (Integer i: intList)
        if (i % 2 == 0)
            sum += i;
        return sum;
}

Because the remainder (%) and unary plus (+=) operators do not apply to Integer objects, you may wonder why the Java compiler compiles the method without issuing any errors. The compiler does not generate an error because it invokes the intValue method to convert an Integer to an int at runtime:

public static int sumEvenInteger(List < Integer > intList) {
    int sum = 0;
    for (Integer i: intList)
        if (i % 2 == 0)
            sum += i.intValue();
        return sum;
}

 

CORE JAVA