The sum that reads one element too many
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.
Highlighted: line 3. Play this one as a puzzle without the answer.
What is wrong
The loop condition uses <= with values.length. Valid indexes run from 0 to length - 1, so on the last iteration i equals values.length and values[i] throws ArrayIndexOutOfBoundsException.
The fix
How to avoid it next time
Use < with length, or an enhanced for loop, which cannot go out of range. Write the loop for the empty and one-element cases first.
Want the background? Read Arrays and the Arrays utilities 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
Frequently asked questions
What is the bug in "The sum that reads one element too many"?
The loop condition uses <= with values.length. Valid indexes run from 0 to length - 1, so on the last iteration i equals values.length and values[i] throws ArrayIndexOutOfBoundsException. The faulty line is line 3: for (int i = 0; i <= values.length; i++) {
How do I fix it?
Replace it with: for (int i = 0; i < values.length; i++) {. Use < with length, or an enhanced for loop, which cannot go out of range. Write the loop for the empty and one-element cases first.
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.