This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes ArrayList throws Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ArrayList throws " Watch "ArrayList throws " New topic

ArrayList throws

santoshkumar savadatti
Ranch Hand

Joined: Apr 27, 2010
Posts: 95
Hi all.
I am still a greenhorn.I wrote the following program:

As far as i can see, there's no problem (but then I'm greenhorn )
But when i run the code, it displays numbers at each position as expected.But it also displays the following message:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 8, Size: 8
at java.util.ArrayList.RangeCheck(
at java.util.ArrayList.get(

and its displayed for different index every time.Sometimes for Index 4 and sometimes for Index 8.
at org.testSample3.example.ListClass.main(
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

The for-each loop will iterate through the values of your list and assign the value to i.
So i get's the values of the elements in your list. Then you try to get the element of the
list at the index of i. And since your list contains a bigger value then the list size it
throws an IndexOutOfBoundsException because you're trying to acces element number 9
when there are only 8 elements.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
santoshkumar savadatti
Ranch Hand

Joined: Apr 27, 2010
Posts: 95
Thank You very much wouter.
I actually thought i does not contain the value at that iteration but the "index" for that iteration.
Thnks again.I modified the program and now it runs perfectly
Just used a different variable int pos =0 and for-each loop required just a small modification:

I agree. Here's the link:
subject: ArrayList throws
jQuery in Action, 3rd edition