Off-By-One Error

Off-by-one error occurs when we have "<=" instead of "<" when we are checking the expression in the loop. The example below will illustrate the problem.

int array[] = new int[5];

for (int i = 0; i <= 5; i++)
   System.out.println(array[i]);

The program above will result in an array out of bounds exception because we will try to display the result for array[5] and the upper bound of the array is only 4. This is because arrays in Java is zero-indexed (the index for the array starts at 0 instead of 1). The correct code is displayed below.

int array[] = new int[5];

for (int i = 0; i < 5; i++)
   System.out.println(array[i]);

Fook Yuen Sin - Team 1