aspose file tools*
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array index out of bound exception " Watch "Array index out of bound exception " New topic
Author

Array index out of bound exception

anu rani
Greenhorn

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");

for(i=0;i<=loca.length;i++)
{
out.println("loca"+"<br>"+loca[i]);


}
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61413
    
  67

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: 687
    
    1
for(i=0;i<=loca.length;i++)


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
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

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.

Henry


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

Joined: Aug 03, 2008
Posts: 9304
    
  17

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