AP® Computer Science A · Unit 2 · Topic 2.8

Off-by-One Errors and Loop Boundaries

An off-by-one error happens when a loop's boundary condition runs one pass too many or too few, usually from mixing up < with ≤. Getting it right means matching the condition to how array indices actually start and end.

A loop's test decides exactly which index gets visited last. For an array of size n, valid indices run from 0 to n-1 — n slots, but the count starts at 0, so the last legal index is always one less than the length. A loop written as i < arr.length stops right after i = n-1, which is correct. Swap that to i ≤ arr.length and the loop takes one extra pass, trying to use index n, which does not exist. That single extra pass is the entire bug.

The mechanism is just arithmetic on the condition, checked fresh before every pass. With i starting at 0 and the test i < n, the loop runs for i = 0, 1, 2, ..., n-1 — n passes total. With i starting at 1 and the test i ≤ n, the loop runs for i = 1, 2, ..., n — also n passes, just shifted up by one. Same number of passes, different indices visited, which is why off-by-one mistakes often don't crash immediately — they silently process the wrong elements or skip one.

This topic sits right behind writing while and for loops: once the loop structure itself is familiar, boundaries are the detail that decides whether the trace table's last row is correct or garbage. It also connects forward to nested loops and array traversal, where a single sloppy boundary in the inner loop gets repeated on every pass of the outer one, multiplying one small error into many wrong values.

Key terms

Off-by-one error
A bug where a loop runs one pass too many or too few because of an incorrect boundary condition.
arr.length
The number of elements in an array, which is always one greater than its highest valid index.
ArrayIndexOutOfBoundsException
The runtime error thrown when code tries to access an array index that does not exist.
Loop boundary
The starting value, ending condition, and increment that together determine exactly which values a loop variable takes.

Watch it explained

  1. How it worksHow does the loop test decide whether the very last index gets visited or skipped?
  2. Worked exampleTrace i ≤ arr.length on an array of size 5 and find the exact pass that goes wrong.
  3. Worked exampleFind how many passes a loop from i = 1 to i ≤ n makes versus i = 0 to i < n.
  4. Common mistakeWhy isn't an array of length 5 indexed from 1 through 5?

Check yourself

Your turn1 of 2
A loop runs with i starting at 1 and continuing while i ≤ 21, incrementing by 1 each pass. How many total passes does it make?

End of topic.