What is Boxing and Unboxing in Java? When to use it
Boxing means converting a primitive data type into its corresponding wrapper object. Unboxing means converting a wrapper object back into its primitive form. Java provides wrapper classes for…
Boxing means converting a primitive data type into its corresponding wrapper object. Unboxing means converting a wrapper object back into its primitive form.
Java provides wrapper classes for all primitive types such as int to Integer, double to Double, and long to Long. This conversion happens automatically in modern Java and is called auto-boxing and auto-unboxing.
Example of Boxing
int x = 10;
Integer obj = x; // Auto-boxing
In this example, the primitive int value is automatically converted into an Integer object.
Example of Unboxing
Integer obj = 20;
int x = obj; // Auto-unboxing
Here, the Integer object is converted back into a primitive int.
Why Boxing and Unboxing Matter
Even though Java handles this conversion automatically, it still creates objects internally. This leads to extra memory usage and can slow down performance when used frequently, especially in loops or large data processing.
Boxing/Unboxing in Streams (Very Important)
Using Object Stream (Less Efficient)
List<Integer> list = Arrays.asList(10, 20, 30);
int sum = list.stream()
.map(x -> x) // Stream<Integer>
.reduce(0, Integer::sum);
In this case, the stream works with Integer objects, so boxing and unboxing may happen during operations.
Using Primitive Stream (Optimized Approach)
Optimized version using primitive stream
int sum = list.stream()
.mapToInt(Integer::intValue) // IntStream
.sum();
Here, the stream works directly with primitive int values, avoiding boxing and unboxing and improving performance.
When to Use Boxing
Use boxing when you need to store values in collections like List, Set, or Map because these collections work with objects, not primitives.
List<Integer> list = new ArrayList<>();
list.add(10); // Boxing happens automatically
When to Avoid Boxing
Avoid boxing when:
You are performing heavy calculations
You are using streams for numeric operations
Instead of:
.map()
Use:
.mapToInt()
.mapToDouble()
Interview Insight
A very common interview question:
Why is IntStream faster than Stream<Integer>?
Answer:
IntStream works with primitive values directly
It avoids boxing and unboxing overhead
It uses less memory and provides better performance
Key Takeaways
Boxing converts primitive to object
Unboxing converts object to primitive
It happens automatically but has a performance cost
Use primitive streams like IntStream to avoid it
Important for optimization and Java interviews