[java] What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

ArrayIndexOutOfBounds means you are trying to index a position within an array that is not allocated.

In this case:

String[] name = { "tom", "dick", "harry" };
for (int i = 0; i <= name.length; i++) {
    System.out.println(name[i]);
}
  • name.length is 3 since the array has been defined with 3 String objects.
  • When accessing the contents of an array, position starts from 0. Since there are 3 items, it would mean name[0]="tom", name[1]="dick" and name[2]="harry
  • When you loop, since i can be less than or equal to name.length, you are trying to access name[3] which is not available.

To get around this...

  • In your for loop, you can do i < name.length. This would prevent looping to name[3] and would instead stop at name[2]

    for(int i = 0; i<name.length; i++)

  • Use a for each loop

    String[] name = { "tom", "dick", "harry" }; for(String n : name) { System.out.println(n); }

  • Use list.forEach(Consumer action) (requires Java8)

    String[] name = { "tom", "dick", "harry" }; Arrays.asList(name).forEach(System.out::println);

  • Convert array to stream - this is a good option if you want to perform additional 'operations' to your array e.g. filter, transform the text, convert to a map etc (requires Java8)

    String[] name = { "tom", "dick", "harry" }; --- Arrays.asList(name).stream().forEach(System.out::println); --- Stream.of(name).forEach(System.out::println);