BackendBench
Coffee
Spot the Bug #132

The loop that prints once

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

easyLogic and control flowbuggy line: 3

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

What is wrong

The semicolon after the for header is an empty statement and is the entire loop body. The loop spins three times doing nothing, then the block runs once, so only one star is printed.

The fix

for (int i = 0; i < 3; i++) {

How to avoid it next time

Always use braces, and let the formatter or a linter flag empty statements.

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

๐Ÿž Play today's puzzleAll 132 bugsโ† #131

Frequently asked questions

What is the bug in "The loop that prints once"?

The semicolon after the for header is an empty statement and is the entire loop body. The loop spins three times doing nothing, then the block runs once, so only one star is printed. The faulty line is line 3: for (int i = 0; i < 3; i++);

How do I fix it?

Replace it with: for (int i = 0; i < 3; i++) {. Always use braces, and let the formatter or a linter flag empty statements.

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.

More tools you might need