The copy that drops the last element
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 last argument of System.arraycopy is the number of elements to copy, not the last index. Passing src.length - 1 leaves the final element of the source behind as zero in the new array.
The fix
How to avoid it next time
Prefer Arrays.copyOf(src, src.length + 1), which does both steps correctly.
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 copy that drops the last element"?
The last argument of System.arraycopy is the number of elements to copy, not the last index. Passing src.length - 1 leaves the final element of the source behind as zero in the new array. The faulty line is line 3: System.arraycopy(src, 0, dst, 0, src.length - 1);
How do I fix it?
Replace it with: System.arraycopy(src, 0, dst, 0, src.length);. Prefer Arrays.copyOf(src, src.length + 1), which does both steps correctly.
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.