41 Java语言基础数组操作的两个常见小问题越界和空指针

1 class Demo3_Array{
2     public static void main(String[] args) {
3             int[] arr = {1,2,3};
4             System.out.println(arr[4]);  //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
5 
6     }
7 }

 

当访问数组中不存在的索引时,会引发越界异常

 

 

 1 class Demo3_Array{
 2     public static void main(String[] args) {
 3             int[] arr = {1,2,3};
 4             System.out.println(arr[4]);  //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
 5             
 6 
 7             arr = null;
 8             System.out.println(arr[0]);//Exception in thread "main" java.lang.NullPointerException
 9     }
10 }

 

当引用赋值为null再去调用数组中的元素,就会引发空指针异常.

posted @ 2017-01-23 20:41  panw3i  阅读(236)  评论(0编辑  收藏  举报