Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array index out of bound exception

 
anu rani
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64967
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Gulsum Ramazanoglu
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1015
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21195
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just change the code to

i.e. replace the <= with <. This is a very basic mistake.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic