Quote

Only he who has seen all the failure will get all the success.

Wednesday, August 20, 2008

java.lang.IndexOutOfBoundsException

This exception is thrown when we try to access an element/object which is not present at all.
Access an element/object which is not present at all????? Not present???? where it is not present???
Well, we associate an index with a list,array or a vector. We use this index (index variable) to access directly a particular element in the array or a particular object in the list.
Remember?

...
int len=somestring.length()+1;
for(int i=0;i<=len;i++)
{
...
System.out.println("char="+somestring.charAt(i));
}
...

i is an index variable or the index for the string object which we use to get each character in the string, like wise for a list and a vector.
Now the value of this index is limited up to the length of the string or the list which we use.
And when we try to assign a value to this index(programatically) which is out of this length,i.e. OutOfBound then the jvm throws this exception.The bound is the length of the string object or the list or the vector.
In the above example we assign the length of the string to an int variable and add 1 to it and iterate through the loop for length + 1 times.The loop will print the characters in the string up to the length of the string but when it comes for the last iteration it will find that there is no element at the specified index because there is no such index at all in the given string and hence the exception.

No comments: