BackendBench
Coffee
Spot the Bug #63

Counting words with a missing entry

A medium 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.

mediumNull handlingbuggy line: 7

Highlighted: line 7. Play this one as a puzzle without the answer.

What is wrong

On the first occurrence of a word counts.get returns null, and assigning it to an int unboxes it, which throws NullPointerException. The line looks like plain arithmetic, so the unboxing is easy to miss.

The fix

counts.merge(w, 1, Integer::sum);

How to avoid it next time

Use merge or getOrDefault when counting. Beware of unboxing a value that can be null.

Want the background? Read Autoboxing and wrapper types 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

๐Ÿž Play today's puzzleAll 132 bugsโ† #62#64 โ†’

Frequently asked questions

What is the bug in "Counting words with a missing entry"?

On the first occurrence of a word counts.get returns null, and assigning it to an int unboxes it, which throws NullPointerException. The line looks like plain arithmetic, so the unboxing is easy to miss. The faulty line is line 7: int c = counts.get(w);

How do I fix it?

Replace it with: counts.merge(w, 1, Integer::sum);. Use merge or getOrDefault when counting. Beware of unboxing a value that can be null.

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.

More tools you might need