The ArrayIndexOutOfBoundsException exception is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
For example see the code snippet below:
String[] vowels = new String[]{"a", "i", "u", "e", "o"}
String vowel = vowels[10]; // throws the ArrayIndexOutOfBoundsException
Above we create a vowels
array with five elements. This will make the array have indexes between 0..4
. On the next line we tried to access the tenth element of the array which is illegal. This statement will cause the ArrayIndexOutOfBoundsException
thrown.
We must understand that arrays in Java are zero indexed. The first element of the array will be at index 0
and the last element will be at index array-size - 1
. So be careful with your array indexes when accessing array elements. For example if you have an array with 5 elements this mean that the index of the array is from 0
to 4
.
If you are trying to iterate an array using for
loop. Make sure the index start from 0 and execute the loop while the index is less than the length of the array, you can get the length of the array using the array length
property. Let’s see the code snippet below:
for (int i = 0; i < vowels.length; i++) {
String vowel = vowels[i];
System.out.println("vowel = " + vowel);
}
Or if you don’t need the index you can simplify your code using the for-each
or enhanced for-loop statement instead of the classic for
loop statement as shown below:
for (String vowel : vowels) {
System.out.println("vowel = " + vowel);
}
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
The tips provided in the article for avoiding this error are helpful. Thanks for sharing!