Oliver Klingefjord Oliver Klingefjord - 11 months ago 37
Java Question

Why am I getting "ArrayOutOfBoundsException" (10) error?

int array[] = {0,0,0,0,0,0,0,0,0,0}
if (array[9] == 0) { //if the array is full, skip this
currentVal = array[i]; //store current value in array
} else {
//store max value of array in medHigh
for (int x = 0; x < 10; x++) {
if (array[x] > medHigh) {
medHigh = array[x];

Answer Source

Simple because your array has length 10 so the maximum index is 9. Arrays in Java are 0-based. It means, that it's indexes are from 0 incl to array.length - 1 incl which in your case is 9.

Java gave you a stacktrace. It looks like following (by the way, A L W A Y S attach it to the question about Exceptions):

java.lang.ArrayIndexOutOfBoundsException: 10
at package.ClassName.methodName(ClassName.java:lineNumber)

Is the line number the number of line in which you call currentVal = array[i];? If yes, it's your answer - i is 10.

If you paste your stack trace, comment my answer for further help. I'll answer with pleasure.