数组--------常见的两个异常数组越界和空指针(三)

1.ArrayIndexOutOfBoundsException:数组索引越界异常

 原因:你访问了不存在的索引。

class Demo7_Exception {
	public static void main(String[] args) {
		int[] arr = new int[5];		
		System.out.println(arr[4]);	
                System.out.println(arr[-1]);		//报错
		System.out.println(arr[5]);	        //报错

	}
}
//注:当访问数组中不存在的索引,会出现索引越界异常

2.NullPointerException:空指针异常

原因:数组已经不在指向堆内存了。而你还用数组名去访问元素。
        int[] arr = {1,2,3};
        arr = null;
        System.out.println(arr[0]);

class Demo7_Exception {
	public static void main(String[] args) {
		int[] arr = new int[5];						//0x0011

		arr = null;
		System.out.println(arr[0]);//注:当数组引用赋值为null,再去调用数组中的元素就会出现      空指针异常
	}
}

猜你喜欢

转载自blog.csdn.net/mqingo/article/details/81702559