Problem category: Logic Problem/ Runtime Error
Diagnosis Difficulty: Easy-medium
Difficulty to Fix: Easy-medium
Array indices in Java always start at 0. This is different from some other languages, notably Python, Matlab, etc..
ex: take an array {2, 5, 1, 3}
The first item is 2. So, the offset from the first item is 0. Thus, the index of the first item is 0.
The second item is that the length of arrays is the total number of items in that array. Because of this, an array with 4 item will have a length a 4, and the last item will have an index of length - 1, or 3. This concept trips a lot of people up, so make sure you fully understand it.
This problem almost always manifests itself when someone tries to use a loop to iterate over an array:
int[] myArray = new int[]{2, 5, 1, 3}; for(int i = 1; i <= myArray.length; ++i) { // do stuff to the array }
This piece of code demonstrates two off-by-one errors:
1. You're starting from the first element in the array, so you skip the first item.
2. You're going until i is greater than myArray.length. This means you will at one point have i = myArray.length. However, this is not a valid array index. Array indices run from [0, length - 1] (using mathematical set notation)
Error messages:
If you're lucky, you will get an error message because you over-stepped the bounds of the array.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Test.main(Test.java:8)
at Test.main(Test.java:8)
For example:
int[] myArray = new int[]{2, 5, 1, 3}; for(int i = 1; i < myArray.length; ++i) { // increase every element in myArray by 5 myArray[i] += 5; }
These are much harder to find because there is no exception telling you what's wrong.
Suggested fixes
Ensure that you are properly indexing your arrays, as well as correctly utilizing the length field of your arrays.
This discussion applies to other types of data structures as well, such as ArrayLists and Vectors which are basically arrays.
int[] myArray = new int[]{2, 5, 1, 3}; for(int i = 0; i < myArray.length; ++i) { // increase every element in myArray by 5 myArray[i] += 5; }
Note: this is not the only way you can get an off by 1 error, though it is probably the most common.