Eventually I got the answer, but it puzzled me for a while.
Why does the following code throws NullPointerException when run?
import java.util.*;
c
Because m.put returns null (which indicates that there's no "previous" value) while you're trying to assign it to int. Replace int p by Integer p and it will work.
This is specified in JLS 5.1.8:
5.1.8 Unboxing Conversion
At run time, unboxing conversion proceeds as follows:
- If r is
null, unboxing conversion throws aNullPointerException
Unrelated to the problem, just a side suggestion with DRY in mind, consider writing it so:
Integer p = m.put("oscar", a == null ? 1 : a++);
It's a bit more readable :)