-1

I have a simple for loop which prints the content of an integer array. It keeps throwing java.lang.ArrayIndexOutOfBoundsException exception. I have been scratching my head for couple of hours not knowing what is that I am doing wrong

public class ReverseArray {
public static void main(String[] args) {

    int[] nums = {100,90,80,70,60,50,40,30,20,10};

    for(int i = 10; i >= 0; i--){
        System.out.print(nums[i] + " ");
    }



   }
 }
sid34
  • 17
  • 2

2 Answers2

0

The ArrayIndexOutOfBoundsException is thrown because you try to access the 11th element in a 10 element array.

Arrays use zero-based indexing, which means that when you do nums[0] you are trying to access the first element of the Array. So:

int[] nums = {100,90,80,70,60,50,40,30,20,10};
System.out.println(nums[0]);

will print

100

As a result of this, when you do nums[10], you are trying to access the 11th element, which doesn't exist. To fix this, you can start on index 9 instead of 10, like:

for(int i = 9; i >= 0; i--){ // "i" starts with a value of 9, so it works
   System.out.print(nums[i] + " ");
}
0

Arrays in most programming language are indexed from 0 by default, so that means the first element which is 100 has an index of 0, so u access it as nums[0]. So from this u can realize that the last element in ur array has an index of 9 which is nums[9] ==10.

ur getting this error because ur trying to access the element at the 10th index even though ur array has elements only upto 9th index i.e nums[0] = 100, nums[1] = 90 ..... nums [9] = 10.

just change the i to 9 like this and it will work like a charm

public class ReverseArray {
public static void main(String[] args) {

int[] nums = {100,90,80,70,60,50,40,30,20,10};

for(int i = 9; i >= 0; i--){
    System.out.print(nums[i] + " ");
}

}
}
Rmcr714
  • 199
  • 1
  • 3
  • 10
  • Not in "any programming language" - there are languages which use 1-based array indexing, and in others it may be 0-based by default, but with options to create arrays with a non-0 lower bound. I think it's generally better to stick to specific statements: arrays in Java definitely are 0-indexed. – Jon Skeet May 24 '21 at 05:57
  • Sure , i got ur point . I think `arrays in most programming languages by default use 0 based indexing` is what u mean – Rmcr714 May 24 '21 at 06:01
  • "Most" is probably accurate, yes. – Jon Skeet May 24 '21 at 06:02