Java 为什么这会导致运行时出现ArrayIndexOutOfBoundsException?

Java 为什么这会导致运行时出现ArrayIndexOutOfBoundsException?,java,arrays,Java,Arrays,代码如下: public class Test { public static void main(String[] args) { int[] a= new int[3]; System.out.print(a[a.length]); } } 为什么这会导致运行时出现ArrayIndexOutofBoundsCeptionWill a.length返回数组中的元素数,这里是3 数组索引从0开始。如果有3个元素,则为0,1,2 没有索引3,因此有

代码如下:

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

为什么这会导致运行时出现ArrayIndexOutofBoundsCeptionWill

a.length
返回数组中的元素数,这里是3

数组索引从0开始。如果有3个元素,则为0,1,2


没有索引3,因此有例外。

索引从
0
开始(不是形式
1
)。因此,在您的例子中,
a
具有索引
0
1
2

但您正在尝试访问索引
3
length
size


使用
System.out.print(a[a.length]-1)

您应该使用:

public class Test{

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

a.length
将返回长度,即3(3个现有字段)。 但是
a[3]
的索引从0开始,上升到2。 使用-1减少长度将返回最后一个真正存在的索引(2)


因此
a[a.length]
(=
a[3]
)会导致数组索引越界异常。

它从0开始,因此必须更改为
[a.length-1]

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

这是
IndexOutOfBoundsException
的层次结构:

 java.lang.Object
    java.lang.Throwable
        java.lang.Exception
            java.lang.RuntimeException
                java.lang.IndexOutOfBoundsException 
有时解决这个问题比较困难。在这些时刻,您可以使用空闲调试器。它将在图形界面中显示每次迭代时每个变量的值


您可以使用
Eclipse
debugger、
Netbeans
visualstudio
code、
Atom
扩展也可以使用。

因为索引从0到2开始,而不是从1到3:)更改为
System.out.print(a[a.length-1])
由于
newint[3]的原因,它不应该编译
publicclassTest
没有解释的代码通常无助于理解问题