Autoboxing and Unboxing
Java can automatically convert between primitive types and their wrapper classes.
1. Autoboxing
Autoboxing = primitive → wrapper object
int x = 10;
Integer num = x;
Java automatically converts:
Integer num = Integer.valueOf(x);
Common examples
int → Integer
double → Double
char → Character
boolean → Boolean
Why is it useful?
Especially with collections:
List<Integer> numbers = new ArrayList<>();
numbers.add(10); // int → Integer automatically
2. Unboxing
Unboxing = wrapper object → primitive
Integer num = 10;
int x = num;
Java automatically converts it roughly to:
int x = num.intValue();
3. Autoboxing in Method Calls
If a method expects a wrapper but you provide a primitive:
void printNumber(Integer num) {
System.out.println(num);
}
int x = 10;
printNumber(x); // int → Integer
Java automatically boxes x.
4. Unboxing in Method Calls
If a method expects a primitive but you provide a wrapper:
void printNumber(int num) {
System.out.println(num);
}
Integer x = 10;
printNumber(x); // Integer → int
Java automatically unboxes x.
5. Autoboxing with Collections
Collections cannot directly store primitive types.
❌ Not allowed:
List<int> numbers;
Instead, use the wrapper:
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
Here:
10 (int)
↓
Integer
↓
List<Integer>
6. Unboxing in Expressions
Java automatically unboxes wrapper objects when primitive operations are needed.
Integer x = 10;
Integer y = 20;
int sum = x + y;
Java effectively does:
int sum = x.intValue() + y.intValue();
Another example:
Integer num = 10;
if (num % 2 == 0) {
System.out.println("Even");
}
num is automatically unboxed to int.
7. Primitive ↔ Wrapper
| Primitive | Wrapper |
|---|---|
boolean |
Boolean |
byte |
Byte |
char |
Character |
short |
Short |
int |
Integer |
long |
Long |
float |
Float |
double |
Double |
8. Complete Example
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Autoboxing
int x = 10;
Integer num = x;
// Unboxing
int y = num;
// Autoboxing in collection
List<Integer> numbers = new ArrayList<>();
numbers.add(20);
// Unboxing from collection
int value = numbers.get(0);
System.out.println(num);
System.out.println(y);
System.out.println(value);
}
}
Easy way to remember
Autoboxing:
int → Integer
Unboxing:Integer → int
Primitive ──autoboxing──> Wrapper
Primitive <──unboxing──── Wrapper
The main reason you need to know this is collections and generics use objects, not primitives.