数组常见的问题

来源:互联网 发布:access数据库的用途 编辑:程序博客网 时间:2024/05/16 18:28
数组常见的问题
1. NullPointerException空指针异常
        原因:引用类型(8种基本数据类型以外的所有类型)变量没有指向任何对象,而访问了对象的属性或者是调用了对象的方法。
案例1如下:
/*** Author:Liu Zhiyong* Version:Version_1* Date:2016年4月5日19:07:10* Desc:数组中最常见的问题:*NullPointerException空指针异常*原因:引用类型(8种基本数据类型以外的所有类型)变量没有指向任何对象,而访问了对象的属性或者是调用了对象的方法。*/class Demo20 {public static void main(String[] args) throws Exception{int[] arr = new int[2];        arr = null; //null让该变量不要引用任何的对象(即不要记录任何的内存地址)System.out.println("这里会被执行吗1");arr[1] = 10;//问题出在这里System.out.println("这里会被执行吗2");System.out.println(arr[1]);}}
案例1结果:
案例1分析:
2.ArrayIndexOutOfBoundsException索引值越界异常
    原因:访问了不存在的索引值
案例2如下:
/*** Author:Liu Zhiyong* Version:Version_1* Date:2016年4月5日19:07:10* Desc:数组中最常见的问题:*2.ArrayIndexOutOfBoundsException* 原因:访问了不存在的索引值*/class Demo20 {public static void main(String[] args) throws Exception{        int[] arr = new int[2];arr[0] = 1;arr[1] = 2;//System.out.println(arr[2]);//访问索引值为2的内存空间存储的值for(int index=0; index<=arr.length; index++){  //问题出在这里,index<=,=的话就越界了System.out.println(arr[index]);}}}
案例2结果:
案例2分析:
0 0
原创粉丝点击