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