English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn about Java automatic boxing and unboxing with examples.
InAutomatic boxing inThe Java compiler will automatically convert the primitive type to its corresponding wrapper class object. For example,
int a = 56; // Auto-boxing Integer aObj = a;
When using Java collections,Auto-boxinghas a great advantage.
import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); //Auto-boxing list.add(5); list.add(6); System.out.println("ArrayList: " + list); } }
Output Result
ArrayList: [5, 6]
In the above example, we created an array list of Integer type. Therefore, the array list can only contain Integer objects.
Note this line,
list.add(5);
Here, we pass the primitive type value. However, sinceAuto-boxing, the primitive values will be automatically converted to Integer objects and stored in the array list.
InUnboxing inThe Java compiler will automatically convert the wrapper class object to its corresponding primitive type. For example,
// Auto-boxing Integer aObj = 56; // Unboxing int a = aObj;
LikeAutomaticBoxingLikeUnboxingCan also be used with Java collections.
import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); //Auto-boxing 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 Result
ArrayList: [5, 6] Value at index 0: 5
In the above example, please note the following line:
int a = list.get(0);
Here, the get() method returns the object at index 0. However, sinceUnboxingThe object is automatically converted to the primitive type int and assigned to the variable a.