The autoboxing and unboxing Java features let you write cleaner and easier-to-read code by allowing you to use either primitive data types or their corresponding wrapper objects. Java then automatically makes the needed conversions in code at runtime.
Conversion | Applied when | |
---|---|---|
Autoboxing | Primitive → Wrapper | A primitive value is:
|
Unboxing | Wrapper → Primitive | A wrapper object is:
|
Autoboxing and unboxing both work for all primitive data types, including char
and boolean
.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Example 1: Autoboxing by parameter passing List<Integer> list = new ArrayList<>(); int i = 8; list.add(i); // converted to: list.add(Integer.valueOf(i)); // Example 2: Unboxing by assignment i = list.get(0); // converted to: i = list.get(0).intValue(); // Example 3: Unboxing by using operators Integer a = new Integer(1); i = (a + 2); // converted to: i = (a.intValue() + 2); |