Java Reference
In-Depth Information
ArrayIndexOutOfBoundsException
Arrays have a fi xed size in Java, and the JVM throws an ArrayIndexOutOfBoundsException
when any attempt is made to access an array element outside of the bounds of the array.
For example, the following statements compile but cause an exception at runtime. Do you
see why?
3. int [] scores = {10, 21, 14, 35};
4. int total = 0;
5. for(int i = 0; i <= scores.length; i++) {
6. total += scores[i];
7. }
8. System.out.println(total);
The problem is that the for loop executes fi ve times with i incrementing from 0 to 4 , but
the array only contains 4 elements. When i equals 4 , an ArrayIndexOutOfBoundsException
occurs on line 6. Here is the output:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 4
at ApiExceptions.main(ApiExceptions.java:6)
As with most situations where this exception occurs, proper code can eliminate the
exception from being thrown. With arrays, take advantage of the new for-each loop
whenever possible to avoid accessing an illegal array element:
for(int score : scores ) {
total += score;
}
Using the length Attribute Properly
A common mistake beginning Java programmers make is to write a for loop that steps
off the end of the array:
for(int i = 0; i <= scores.length; i++)
The proper syntax is to use < instead of <= when using the length attribute of the array:
for(int i = 0; i < scores.length; i++)
This scenario makes a good exam question, so keep an eye out for loops that generate an
ArrayIndexOutOfBoundsException .
Search WWH ::




Custom Search