In this tutorial, we will learn about the Java Autoboxing and Unboxing with the help of an example.
Autoboxing: Converting a primitive value into an object of the corresponding wrapper class is called autoboxing. For example, converting int to Integer class.
Unboxing: Converting an object of a wrapper type to its corresponding primitive value is called unboxing. For example conversion of Integer to int.
Java AutoBoxing
import java.util.ArrayList;
class Codemistic {
public static void main(String[] args) {
ArrayList list = new ArrayList<>();
//autoboxing
list.add(5);
list.add(6);
System.out.println("ArrayList: " + list);
}
}
Output:
ArrayList: [5, 6]
Java Unboxing
import java.util.ArrayList;
class Codemistic {
public static void main(String[] args) {
ArrayList 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