Video in progress
What are autoboxing and unboxing, and what problems can they cause?
Autoboxing is the automatic conversion of a primitive into its wrapper class (int to Integer), and unboxing is the reverse. It's convenient, but it causes an NPE when unboxing null, extra objects in loops, and wrong results when you compare with ==.
📖 Answer
List<Integer> list = new ArrayList<>();
list.add(5); // autoboxing: Integer.valueOf(5)
int x = list.get(0); // unboxing: intValue()
Where it bites:
NPE:
Map<String, Integer> stock = new HashMap<>();
int n = stock.get("olma"); // null -> int: NullPointerException
The safe form: stock.getOrDefault("olma", 0).
Performance:
Long sum = 0L;
for (long i = 0; i < 1_000_000; i++) sum += i; // a new Long on every step
With long sum it's several times faster.
Comparison: comparing Integers with == works for small numbers and not for large ones (because of caching).
The rule: primitives for calculations, wrapper classes in collections and wherever a value can be null.
Sign up to mark studied questions and save your progress.