public class OffByOneErrorExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i <= numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
The problem is this line:
i <=numbers . length
Array index starts from 0 and ends at numbers.length - 1.
For this array:
{10, 20, 30, 40, 50}
Valid indexes are:
0, 1, 2, 3, 4
But when i becomes 5, the program tries to access:
numbers[5]
That does not exist, so Java gives:
ArrayIndexOutOfBoundsException
public class OffByOneErrorFixed {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.