Autoboxing Pitfalls
Null unboxing and == traps.
Convenience Has Traps
Autoboxing makes code cleaner, but it hides conversions that can cause surprising bugs. The two biggest traps are null unboxing and identity comparison with ==.
This lesson shows how to avoid both.
The Null Unboxing Trap
If a wrapper holds null and you unbox it to a primitive, Java throws a NullPointerException.
This is easy to miss because the code looks like a simple assignment.
public class Main {
public static void main(String[] args) {
Integer maybe = null;
try {
int value = maybe;
System.out.println(value);
} catch (NullPointerException e) {
System.out.println("Cannot unbox null!");
}
}
}All lessons in this course
- Primitive vs Wrapper Types
- Autoboxing and Unboxing
- Parsing and Valueof
- Autoboxing Pitfalls