Autoboxing is the automatic conversion of primitive types (int, double, etc.) into their corresponding wrapper objects (Integer, Double, etc.). Unboxing is the reverse conversion of a wrapper object back to a primitive.
It works automatically during assignment, method parameters, and collections:
List<Integer> numbers = new ArrayList<>(); numbers.add(5); // Example of autoboxing: 5 (int) -> Integer(5) int value = numbers.get(0); // Unboxing: Integer(5) -> 5
Risks:
Can the following code throw an exception? Why?
Integer x = null; int y = x;
Answer: The code throws a NullPointerException because when attempting to execute int y = x;, unboxing occurs from null to a primitive, and null cannot be converted to int.
Story
int.Story
Integer as a key for caching, not considering that values -128...127 are cached, while others are not. Because of this, == suddenly started giving incorrect results, leading to incorrect data removal from the cache.Story
In the REST API, nullable values came in. Simple unboxing of the incoming Integer sometimes caused crashes due to unexpected null instead of a number from the client.