-1

This is the code:

public class Test {
    public static void main(String[] args) {
        int[] a= new int[3];
        System.out.print(a[a.length]);
    }
}

Why does this result in an ArrayIndexOutOfBoundsExceptionwill at run-time?

jhamon
  • 3,603
  • 4
  • 26
  • 37
Shroomy
  • 23
  • 3

5 Answers5

3

a.length return the number of elements in the array, here it's 3.

Array index starts at 0. With 3 elements, it goes 0,1,2.

There is no index 3, hence the exception.

jhamon
  • 3,603
  • 4
  • 26
  • 37
0

Index starts from 0 (not form 1). So, in your case a has the index 0, 1 and 2.

But you are trying to access index 3 (length or size).

Use System.out.print(a[a.length]-1); instead.

Rene Knop
  • 1,788
  • 3
  • 15
  • 27
Sai Prasad
  • 286
  • 1
  • 2
  • 13
0

You should use that:

public class Test{

     public static void main(String []args){
        int[] a= new int[3];
        System.out.print(a[a.length-1]);
    }
}

Explanation:

a.length will return the length and that is 3 (3 existing fields). But the index couting for a[3] starts with 0 and goes up to 2. Reducing the length with -1 returns the last really existing index (2).

So a[a.length] (= a[3]) causes the Array Index Out Of Bounds Exception.

Rene Knop
  • 1,788
  • 3
  • 15
  • 27
Harsh Kumrawat
  • 160
  • 1
  • 2
  • 16
0

It starts from 0 so you must Change to [a.length - 1]

 public class Test{
       public static void main(String []args){
          int[] a= new int[3];
          System.out.print(a[a.length-1]);
       }
    }
khaled_bhar
  • 257
  • 1
  • 4
  • 21
-1

This is the hierarchy of IndexOutOfBoundsException:

 java.lang.Object
    java.lang.Throwable
        java.lang.Exception
            java.lang.RuntimeException
                java.lang.IndexOutOfBoundsException 

It is sometimes harder to solve it. During those moments, you can use IDLE debugger. It will show you the value of each variable at each iteration in the graphical interface.

You can use Eclipse debugger, Netbeans, Visual Studio code, Atom extensions works as well.

Ralf
  • 16,086
  • 4
  • 44
  • 68