What exception is java.lang.ArrayIndexOutOfBoundsException, and how do I prevent that exception from occurring?

Asked 2 years ago, Updated 2 years ago, 144 views

What is the meaning of ArrayIndexOutOfBoundsException? How can I handle this exception?

The following source code is an example of where this exception occurs.

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

java indexoutofboundsexception array

2022-09-22 21:32

1 Answers

The answer to the first question is clearly described in this document.

Exception to inform you that you have accessed an array using an invalid index. The index must be greater than 0 or less than the size of the array.

For example:

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

Be careful when you use the index of an array.

Sometimes you mistake the starting index of an array for 1. Therefore, there are cases of incorrect coding as follows.

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

In the above case, an exception will occur when the first element (index 0) passes and the index is 5. Valid indexes range from 0 to 4. Therefore, it is right to use the above for statement as follows:

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


2022-09-22 21:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.