常见问题_数组索引越界异常与常见问题_空指针异常

数组的常见操作
观察一下代码,运行后会出现什么结果。
public static void main(String[] args) {
     int[] arr = {1,2,3};
 System.out.println(arr[3]);
     }
/*
数组的索引编号从0开始,一直到"数组的长度-1"为止
如果访问数组元素的时候,索引编号并存在,那么将会发生
数组索引越界异常
ArrayIndexOutOfBoundsException
原因:索引写错了
解决:修改成为存在正确的索引编号
 */
public class day01 {
    public static void main(String[] args) {
        int[] array={15,25,35};
        System.out.println(array[0]);
        System.out.println(array[1]);
        System.out.println(array[2]);
        //错误写法
        //并存在3号元素,所有发生异常
        System.out.println(array[3]);
    }
}

 

创建数组,赋值3个元素,数组的索引就是0,1,2,没有3索引,因此我们不能访问数组中不存在的索引,程序运
行后,将会抛出 ArrayIndexOutOfBoundsException 数组越界异常。在开发中,数组的越界异常是不能出现的,一
旦出现了,就必须要修改我们编写的代码。
 
 
数组空指针异常
观察一下代码,运行后会出现什么结果。
public static void main(String[] args) {
 int[] arr = {1,2,3};
 arr = null;
 System.out.println(arr[0]); 
}
/*
    所有的引用类型类型变量,都可以赋值为一个null值,但是其中代表其中什么都没有
    数组必须进行new初始化才能使用其中的元素

    那么将会发生
    空指针异常 java.lang.NullPointerException

    原因:忘了new
    解决:补上new
 */
public class day02 {
    public static void main(String[] args) {
        int[] array = null;
        // array = new int[3];
        System.out.println(array[0]);
    }
}
arr = null 这行代码,意味着变量arr将不会在保存数组的内存地址,也就不允许再操作数组了,因此运行的时候
会抛出 NullPointerException 空指针异常。在开发中,数组的越界异常是不能出现的,一旦出现了,就必须要修
改我们编写的代码。
空指针异常在内存图中的表现

 

 


 

posted @ 2022-06-29 17:35  zj勇敢飞,xx永相随  阅读(151)  评论(0编辑  收藏  举报