What is autoboxing in Java?
Autoboxing is the automatic conversion of a primitive like int into its wrapper object like Integer, and unboxing is the reverse. Java does this for you so primitives can be used where objects are required, such as inside collections. It is convenient but can add hidden overhead in tight loops.
- Autoboxing automatically converts a primitive like int into its wrapper Integer.
- Unboxing is the reverse, converting a wrapper back into a primitive.
- It lets primitives work with collections, which store objects, not primitives.
Why it exists
Collections like ArrayList can only hold objects, not primitives. Autoboxing lets you add an int to a List of Integer without writing the conversion yourself.
List<Integer> nums = new ArrayList<>();
nums.add(5); // autoboxing: int 5 -> Integer
int first = nums.get(0); // unboxing: Integer -> int
The gotcha
Autoboxing creates objects, so doing it millions of times in a loop can slow things down and use extra memory. It can also cause a surprise NullPointerException if you unbox a null Integer.
Mention the null unboxing trap: unboxing a null Integer throws a NullPointerException. Pointing out both the convenience and the hidden cost shows you understand the feature beyond the surface.
Frequently asked questions
What is a downside of autoboxing?
It can create hidden objects in loops and cause a NullPointerException if a null wrapper is unboxed into a primitive.
Why can collections not store primitives directly?
Generic collections work with objects, so primitives are boxed into wrapper classes like Integer or Double to be stored.
Common follow up questions
Related interview questions
Want the full Java guide?
Read every Java concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the Java guide All Java questions