A null check that does not protect
A medium Java puzzle in the logic and control flow 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 5. Play this one as a puzzle without the answer.
What is wrong
A single & is the non-short-circuit AND, so both sides are always evaluated. When items is null, items.size() still runs and throws NullPointerException, defeating the null check. && stops after the first false.
The fix
How to avoid it next time
Use && and || for conditions. Single & and | are for bit operations.
Want the background? Read Loops, labels and do-while in the Java concepts library.
About logic and control flow
Operator precedence, missing break statements, short-circuit evaluation and loop conditions that never change are simple to write and tiring to spot after a long day of reviews.
In code review: Read conditions out loud with explicit parentheses, check every switch branch for break or return, and make sure each loop makes progress toward its exit.
More puzzles in this family
Frequently asked questions
What is the bug in "A null check that does not protect"?
A single & is the non-short-circuit AND, so both sides are always evaluated. When items is null, items.size() still runs and throws NullPointerException, defeating the null check. && stops after the first false. The faulty line is line 5: return items != null & items.size() > 0;
How do I fix it?
Replace it with: return items != null && !items.isEmpty();. Use && and || for conditions. Single & and | are for bit operations.
How do I catch logic and control flow in code review?
Read conditions out loud with explicit parentheses, check every switch branch for break or return, and make sure each loop makes progress toward its exit.
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.