1、数组越界异常
(1)数组越界异常ArrayIndexOutOfBoundsException
(2)每个数组的索引都有一个范围,即0~length-1。在访问数组的元素时,索引不能超出这个范围,否则程序会报错
1 public class ArrayDemo06 { 2 public static void main(String[] args) { 3 int[] arr = new int[4]; // 定义一个长度为4的数组 4 System.out.println("arr[0]=" + arr[4]); // 通过角标4访问数组元素 5 } 6 }
运行结果:
2、空指针异常
(1)空指针异常NullPointerException
(2)在使用变量引用一个数组时,变量必须指向一个有效的数组对象,如果该变量的值为null,则意味着没有指向任何数组,此时通过该变量访问数组的元素会出现空指针异常
1 public class ArrayDemo07 { 2 public static void main(String[] args) { 3 int[] arr = new int[3]; // 定义一个长度为3的数组 4 arr[0] = 5; // 为数组的第一个元素赋值 5 System.out.println("arr[0]=" + arr[0]); // 访问数组的元素 6 arr = null; // 将变量arr置为null 7 System.out.println("arr[0]=" + arr[0]); // 访问数组的元素 8 } 9 }
运行结果: