In autoboxing, the Java compiler automatically converts primitive types into their corresponding wrapper class objects. For example,
int a = 56;
// autoboxing
Integer aObj = a;
Autoboxing has a great advantage while working with Java collections.
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
//autoboxing
list.add(5);
list.add(6);
System.out.println("ArrayList: " + list);
}
}
Output
ArrayList: [5, 6]
In the above example, we have created an array list of Integer type. Hence the array list can only hold objects of Integer
type.
Notice the line,
list.add(5);
Here, we are passing primitive type value. However, due to autoboxing, the primitive value is automatically converted into an Integer
object and stored in the array list.
In unboxing, the Java compiler automatically converts wrapper class objects into their corresponding primitive types. For example,
// autoboxing
Integer aObj = 56;
// unboxing
int a = aObj;
Like autoboxing, unboxing can also be used with Java collections.
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
//autoboxing
list.add(5);
list.add(6);
System.out.println("ArrayList: " + list);
// unboxing
int a = list.get(0);
System.out.println("Value at index 0: " + a);
}
}
Output
ArrayList: [5, 6]
Value at index 0: 5
In the above example, notice the line,
int a = list.get(0);
Here, the get()
method returns the object at index 0. However, due to unboxing, the object is automatically converted into the primitive type int
and assigned to the variable a.