The default that is not used
A hard Java puzzle in the null handling family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 7. Play this one as a puzzle without the answer.
What is wrong
getOrDefault returns the default only when the key is absent. The key exists with a null value, so null is returned and toUpperCase throws NullPointerException. Maps that allow null values blur the difference between missing and empty.
The fix
How to avoid it next time
Avoid storing null values in maps. Use Optional or a sentinel, or default with Objects.requireNonNullElse.
Want the background? Read Map idioms: merge, compute, entrySet in the Java concepts library.
About null handling
NullPointerException is still the most common production exception. Chained calls, auto-unboxing, maps that return null for missing keys and Optional used the wrong way all hide a null until the worst moment.
In code review: Trace each dereference back to where the value comes from and decide whether it can be null. Be wary of Optional.get, getOrDefault on null values and unboxing of Integer fields.
More puzzles in this family
Frequently asked questions
What is the bug in "The default that is not used"?
getOrDefault returns the default only when the key is absent. The key exists with a null value, so null is returned and toUpperCase throws NullPointerException. Maps that allow null values blur the difference between missing and empty. The faulty line is line 7: String nick = nicknames.getOrDefault("ann", "anonymous");
How do I fix it?
Replace it with: String nick = java.util.Objects.requireNonNullElse(nicknames.get("ann"), "anonymous");. Avoid storing null values in maps. Use Optional or a sentinel, or default with Objects.requireNonNullElse.
How do I catch null handling in code review?
Trace each dereference back to where the value comes from and decide whether it can be null. Be wary of Optional.get, getOrDefault on null values and unboxing of Integer fields.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.