Saturday 16 February 2019

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?



What does ArrayIndexOutOfBoundsException mean and how do I get rid of it?




Here is a code sample that triggers the exception:



String[] name = { "tom", "dick", "harry" };
for (int i = 0; i <= name.length; i++) {
System.out.println(name[i]);
}

Answer



Your first port of call should be the documentation which explains it reasonably clearly:





Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.




So for example:



int[] array = new int[5];
int boom = array[10]; // Throws the exception



As for how to avoid it... um, don't do that. Be careful with your array indexes.



One problem people sometimes run into is thinking that arrays are 1-indexed, e.g.



int[] array = new int[5];
// ... populate the array here ...
for (int index = 1; index <= array.length; index++)
{
System.out.println(array[index]);
}



That will miss out the first element (index 0) and throw an exception when index is 5. The valid indexes here are 0-4 inclusive. The correct, idiomatic for statement here would be:



for (int index = 0; index < array.length; index++)


(That's assuming you need the index, of course. If you can use the enhanced for loop instead, do so.)


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...