File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Array index out of bounds error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array index out of bounds error " Watch "Array index out of bounds error " New topic

Array index out of bounds error

G. Graz
Ranch Hand

Joined: Oct 23, 2006
Posts: 30
I am getting an "java.lang.ArrayIndexOutOfBoundsException" error in the code below I think it might be at sum = average[i]; but I do not see why I am throwing that error ? The array element has an index of 16 , reading off a .txt file . Ok, please let me know if you can see what I am doing incorrectly ? Thank you.

Henry Wong

Joined: Sep 28, 2004
Posts: 20535

Besides the file, method, and line number, the exception also tells you which index was being referrenced. It would help if you give us the stacktrace -- at least the fist few lines of it.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46405
You need to check the format of a for loop when iterating an array. Unfortunately there isn't a good example in the Java Tutorials; you should find something in your textbook. Look at the binary operators very carefully.
vaibhav mishra
Ranch Hand

Joined: Jun 18, 2008
Posts: 168
assuming that you have 16 elements for input here is what you did wrong

consider this line

you declare a string array with 16 elements , the index being 0 to 15( 15(1st to 15th index ) + 1(0th index ) )
it takes elements from intFile(1st element at 0th index ... 4th element at 3rd index and 16th element at 15th index)
so avarage[15] infact represents your 16th element(15 is the index here)

in the following array iteration for loop at this line

the <= makes it iterate from 'zero' to 16 th (i.e., your array should have 17 elements)
so just remove '=' sign and change line to

Note: maxList.size() return 16 because you array has 16 elements indexed from 'zero' to 15

I agree. Here's the link:
subject: Array index out of bounds error
It's not a secret anymore!