Home > Mobile >  ArrayIndexOutOfBoundException for itterating through an array using a for loop
ArrayIndexOutOfBoundException for itterating through an array using a for loop

Time:12-16

This code is throwing an out of bound exception, but I have no idea why. I have tried to put i < x.length and i <= x.length-1, but nothing works. I know that it alsways starts with a 0, but this should be fine, right?

public class Test {

public static void main(String[] args) { 
    int[] x = new int[5]; 
    int i; 
    for (i = 0; i <= x.length; i  ) 
        x[i] = i; 
        System.out.println(x[i]); 
}

}

CodePudding user response:

You are correct that 0 is the first index. But that means that the last index is one less than the size of the array. So if the loop counter reaches the length of the array then it is outside the bounds for an index into that array.

You need to replace the <= with < in the for loop condition.

for (i = 0; i < x.length; i  ) {
  x[i] = i;
  System.out.println(x[i]); 
}

CodePudding user response:

  1. Array index starts from 0 and here you have 0 to 4 index numbers, but length property starts from 1 so your length here is 5. So you should change <= to <
  2. After your iteration within the for loop your i value would be equal to 5 that's why it'll exit the for loop but there's a problem below waiting for you. You want to retrieve i.th index of x but it's also out of bounds.
  3. If you want to retrieve last item of an index you can use "x.length-1"
  • Related