Autoboxing is an automatic conversion of a primitive to its wrapper class.
int x = 20;
Integer y = x; // autoboxing
Unboxing is an automatic conversion of a wrapper object back to its primitive form.
Integer a = 20;
int b = a; // unboxing
Warning
Autoboxing/unboxing can cause performance hits in tight loops or large data structures.
Primitive ↔ Wrapper Types
Primitive | Wrapper Class |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
Example
List<Integer> nums = new ArrayList<>();
nums.add(5); // int → Integer (autoboxing)
int n = nums.get(0); // Integer → int (unboxing)
Tip
Primitives are more performant, but wrappers are required in collections like List, Map, etc.
Parent: _Casting & Types