1.数组操作的的常见错误:数组索引越界异常(ArrayIndexOutOfBoundsException)和空指针异常(NullPointerException)
数组索引越界异常:当程序运行访问了数组中不存在的索引时就会出现数组索引异常。
如果运行结果中出现 “Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at DemoArray3.main(DemoArray3.java:5)” 就要考虑是数组中引用了不存在的索引
class DemoArray3 {
public static void main(String[] args){
int[] arr = new int[]{1,2,3,4};
System.out.println(arr[4]); // 所要访问的数据值大于数组的长度,所以报错
}
}
空指针异常:一般都是变量为空导致的,也就是定义变量没有赋初值
如果运行结果中出现 “ Exception in thread "main" java.lang.NullPointerException at DemoArray2.main(DemoArray2.java:15) “ 就要考虑是否数组中出现数组未赋初值。
class DemoArray2 {
public static void main(String[] args){
int[][] arr = new int[3][];
System.out.println(arr[0][0]);
}
}
在这里由于未指定一维数组的大小,所以二维数组中一维数组的值不知道,也就不存在默认值 0 ,所以就会报空指针异常的错误。
2.数组赋值的两种格式
格式一:
class DemoArray2 {
public static void main(String[] args){
int[] arr = new int[]{1,2,3}; //错误赋值:int[] arr = new int[3]{1,2,3};
}
System.out.println(arr[0]);
}
格式二:
class DemoArray2 {
public static void main(String[] args){
int[] arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
}
System.out.println(arr[0]);
}