jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Array index out of bound exception 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 bound exception " Watch "Array index out of bound exception " New topic

Array index out of bound exception

anu rani

Joined: Aug 29, 2006
Posts: 14
I am getting Array index out of bound exception so please help in solving the error
int i;
String[] loca=new String[10];
if(request.getParameter("location") != null)
loca = request.getParameterValues("location");


Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63343

Please take the time to choose the correct forum for your posts. This forum is for questions on JSP.

This post has been moved to a more appropriate forum.

[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Gulsum Ramazanoglu
Ranch Hand

Joined: Jun 27, 2008
Posts: 51
Anu hi

I think the problem is that; in the line

with the specification "loca[i]", you try to use an array element
with an index number 0... An array cant have 0th element...
Its because, at the beginning of your for loop, your index i is
starting with the value 0...
I think, somehow you must avoid using 0th element in the array..
Then the problem drops automatically

Have a beautiful day..
Norm Radder
Ranch Hand

Joined: Aug 10, 2005
Posts: 691

The last element in the array has an index = length of array - 1

What does the <= test above allow the value of i to be?
Gulsum Ramazanoglu
Ranch Hand

Joined: Jun 27, 2008
Posts: 51
Anu hi again my dear, I do apologize for mistakenly misleading you .. An array begins with 0th element and I was wrong in my comment.. Please disregard it.

Ok, from now on I wont be "good" for others for some time.. its rather harmful for I am still a newbie!
Henry Wong

Joined: Sep 28, 2004
Posts: 20146

BTW, an array index out of bounds expception actually report the index of the member that is being accessed, when it is printed. You can use this as a way to figure out why the logic is trying to deference an invalid member.


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

Joined: Aug 03, 2008
Posts: 9435

Just change the code to

i.e. replace the <= with <. This is a very basic mistake.

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
I agree. Here's the link: http://aspose.com/file-tools
subject: Array index out of bound exception
It's not a secret anymore!