RSS
Follow Us
Contribute
 
 
 
 
Print Preferences

Java.lang.IndexOutOfBoundsException

 

From $1

Table of contents
  1. 1. Cause
  2. 2. Solution
  3. 3. Additionally

Cause

This exception is thrown in java when the index is higher than the size of a vector, arraylist, array etc... Ex:

ArrayList<String> arr = new ArrayList<String>();
arr.add("someStringHere");
for (int i = 0 ; i < 5 ; i++) {
	arr.get(i);
} 

The above example will throw IndexOutOfBoundsException,because the arraylist contains only 1 string and the index is going further than 0.  (Also in Java the indices start with 0.)

Solution

The thrown exception shows the line number in which the problem has occured. The exception thrown for the above example is like this:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
	at java.util.ArrayList.RangeCheck(Unknown Source)
	at java.util.ArrayList.get(Unknown Source)
	at SomePackage.SomeClass.main(SomeClass.java:16)

For this example the problem has occured in line 16. Additionally Index: 1 shows the index that we tried to reach and Size: 1 tells us the actual size of the variable.

Additionally

IndexOutOfBoundsException is inherited to ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException.

 
 
 
 
 
Creative Commons License
All content is licensed under a Creative Commons Attribution-Noncommercial 3.0 License.
Powered by MindTouch Core v.9.02.2