BackendBench
Coffee
Spot the Bug #5

Reversing starts one past the end

A easy Java puzzle in the off-by-one errors family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

easyOff-by-one errorsbuggy line: 3

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

What is wrong

The loop starts at s.length(), which is not a valid index, so charAt throws StringIndexOutOfBoundsException on the first iteration. Shifting the start fixes it only if the bound changes too: the loop must also reach index 0.

The fix

for (int i = s.length() - 1; i >= 0; i--) {

How to avoid it next time

When counting down, start at length - 1 and keep going while i >= 0. Or simply use new StringBuilder(s).reverse().

Want the background? Read StringBuilder and string building in the Java concepts library.

About off-by-one errors

Loop bounds, indexes and lengths are the oldest source of bugs in programming. Java arrays and lists are zero-based, so the last valid index is length minus one, and ranges such as substring use an inclusive start and an exclusive end.

In code review: Check every loop condition against the first and last element, and ask what happens with zero or one element. Prefer enhanced for loops, streams and library methods that remove manual index arithmetic.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #4#6 โ†’

Frequently asked questions

What is the bug in "Reversing starts one past the end"?

The loop starts at s.length(), which is not a valid index, so charAt throws StringIndexOutOfBoundsException on the first iteration. Shifting the start fixes it only if the bound changes too: the loop must also reach index 0. The faulty line is line 3: for (int i = s.length(); i > 0; i--) {

How do I fix it?

Replace it with: for (int i = s.length() - 1; i >= 0; i--) {. When counting down, start at length - 1 and keep going while i >= 0. Or simply use new StringBuilder(s).reverse().

How do I catch off-by-one errors in code review?

Check every loop condition against the first and last element, and ask what happens with zero or one element. Prefer enhanced for loops, streams and library methods that remove manual index arithmetic.

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