What causes a java.lang.ArrayIndexOutOfBoundsExcep

2019-09-10 03:02发布

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]);
}

24条回答
【Aperson】
2楼-- · 2019-09-10 03:07

For any array of length n, elements of the array will have an index from 0 to n-1.

If your program is trying to access any element (or memory) having array index greater than n-1, then Java will throw ArrayIndexOutOfBoundsException

So here are two solutions that we can use in a program

  1. Maintaining count:

    for(int count = 0; count < array.length; count++) {
        System.out.println(array[count]);
    }
    

    Or some other looping statement like

    int count = 0;
    while(count < array.length) {
        System.out.println(array[count]);
        count++;
    }
    
  2. A better way go with a for each loop, in this method a programmer has no need to bother about the number of elements in the array.

    for(String str : array) {
        System.out.println(str);
    }
    
查看更多
beautiful°
3楼-- · 2019-09-10 03:08

ArrayIndexOutOfBoundsException name itself explains that If you trying to access the value at the index which is out of the scope of Array size then such kind of exception occur.

In your case, You can just remove equal sign from your for loop.

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

The better option is to iterate an array:

for(String i : name )
      System.out.println(i);
查看更多
甜甜的少女心
4楼-- · 2019-09-10 03:09

This error is occurs at runs loop overlimit times.Let's consider simple example like this,

class demo{
  public static void main(String a[]){

    int[] numberArray={4,8,2,3,89,5};

    int i;

    for(i=0;i<numberArray.length;i++){
        System.out.print(numberArray[i+1]+"  ");
    }
}

At first, I have initialized an array as 'numberArray'. then , some array elements are printed using for loop. When loop is running 'i' time , print the (numberArray[i+1] element..(when i value is 1, numberArray[i+1] element is printed.)..Suppose that, when i=(numberArray.length-2), last element of array is printed..When 'i' value goes to (numberArray.length-1) , no value for printing..In that point , 'ArrayIndexOutOfBoundsException' is occur.I hope to you could get idea.thank you !

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-09-10 03:12

So much for this simple question, but I just wanted to highlight a new feature in Java which will avoid all confusions around indexing in arrays even for beginners. Java-8 has abstracted the task of iterating for you.

int[] array = new int[5];

//If you need just the items
Arrays.stream(array).forEach(item -> { println(item); });

//If you need the index as well
IntStream.range(0, array.length).forEach(index -> { println(array[index]); })

What's the benefit? Well, one thing is the readability like English. Second, you need not worry about the ArrayIndexOutOfBoundsException

查看更多
Fickle 薄情
6楼-- · 2019-09-10 03:13

To put it briefly:

In the last iteration of

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

i will equal name.length which is an illegal index, since array indices are zero-based.

Your code should read

for (int i = 0; i < name.length; i++) 
                  ^
查看更多
啃猪蹄的小仙女
7楼-- · 2019-09-10 03:14

For your given array the length of the array is 3(i.e. name.length = 3). But as it stores element starting from index 0, it has max index 2.

So, instead of 'i**<=name.length' you should write 'i<**name.length' to avoid 'ArrayIndexOutOfBoundsException'.

查看更多
登录 后发表回答