BackendBench
Coffee
Spot the Bug #3

Page one skips the first page

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

mediumOff-by-one errorsbuggy line: 6

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

What is wrong

With 1-based page numbers the first page must start at offset 0. page * PAGE_SIZE gives 20 for page 1, so the first twenty rows are never returned and every page is shifted by one. Spring Data PageRequest is 0-based, which makes the mismatch easy to introduce.

The fix

return (page - 1) * PAGE_SIZE;

How to avoid it next time

Decide once whether page numbers are 0-based or 1-based, name the parameter accordingly and convert at the boundary only.

Want the background? Read Spring Data repositories 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โ† #2#4 โ†’

Frequently asked questions

What is the bug in "Page one skips the first page"?

With 1-based page numbers the first page must start at offset 0. page * PAGE_SIZE gives 20 for page 1, so the first twenty rows are never returned and every page is shifted by one. Spring Data PageRequest is 0-based, which makes the mismatch easy to introduce. The faulty line is line 6: return page * PAGE_SIZE;

How do I fix it?

Replace it with: return (page - 1) * PAGE_SIZE;. Decide once whether page numbers are 0-based or 1-based, name the parameter accordingly and convert at the boundary only.

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