当我们访问索引大于数组大小的数组时,抛出此java.lang.ArrayIndexOutOfBoundsException
。
PS阵列索引以0开头
ArrayExample.java
package com.mkyong;
public class ArrayExample {
public static void main(String[] args) {
// array of 3
int[] num = new int[3];
num[0] = 1;
num[1] = 2;
num[2] = 3;
num[3] = 4; //ArrayIndexOutOfBoundsException: 3
System.out.println("num[0] : " + num[0]);
System.out.println("num[1] : " + num[1]);
System.out.println("num[2] : " + num[2]);
System.out.println("num[3] : " + num[3]); //ArrayIndexOutOfBoundsException: 3
}
}
输出量
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at com.mkyong.calculator.ArrayExample.main(ArrayExample.java:13)
参考文献
翻译自: https://mkyong.com/java/java-arrayindexoutofboundsexception-example/