Javaexercise.com

Java Autoboxing and Unboxing

Autoboxing is a term in Java which is used to refer automatic conversion of primitive type value to its wrapper class object. This automatic conversion is done internally by the Java compiler.

In the same manner, conversion of a wrapper class object to its primitive type is called unboxing in Java.

Lets understand it by a simple example.

Integer a = 10; // Autoboxing
int b = a; // Unboxing

In Java, each primitive type has its wrapper class. See the below table to understand available wrapper classes. All the wrapper classes belong to java.lang package.

# Primitive Type Wrapper Class
1 byte Byte
2 short Short
3 char Character
4 int Integer
5 long Long
6 float Float
7 double Double
8 boolean Boolean

Java Autoboxing Example

The Java compiler applies autoboxing when a primitive value is:

  • Passed as an argument to a method that expects an object of the corresponding wrapper class.
  • Assigned to a reference variable of the corresponding wrapper class.

Let's see the both scenario in the below example.

// Autoboxing Example
public class Demo {
    // First parameter is an object of Integer wrapper class
    static boolean equal(Integer x, int y) {
        if(x.intValue() == y)
            return true;
        return false;
    }
    public static void main(String[] args) {
        Integer a = 10; // Assigned primitive value to its wrapper class
        System.out.println(a);
        // Passing primitive value as an argument
        boolean b = equal(10,10);
        System.out.println(b);
    }
}

Output:

10
true

In the above example, equal() method takes two parameters one is object of Integer class and second is primitive type int. At the time of calling, we provide both the arguments as primitive int type then Java compiler internally performed autoboxing and pass first argument as an object of Integer wrapper class.



Java Unboxing Example

The Java compiler applies unboxing when an object of a wrapper class is:

  • Passed as an argument to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.

Let's see the both scenario in the below example.

// Unboxing Example
public class Demo {
    // Both parameters are primitive type
    static boolean equal(int x, int y) {
        if (x == y) // Unboxing internally
            return true;
        return false;
    }
    public static void main(String[] args) {
        Integer a = 10;
        System.out.println(a);
        // Passing wrapper class object as an argument
        boolean b = equal(a,10);
        System.out.println(b);
    }
}

Output:

10
true

In the above example, equal() method takes two primitive type parameters. At the time of calling, we provide first argument as a wrapper class object and other one as primitive type then Java compiler internally performed unboxing and pass first argument as a primitive argument.