基础第一阶段day05——索引越界异常、空指针异常

ArrayIndexOutOfBoundsException 数组越界异常

public class Test01 {
    public static void main(String[] args) {
        int[] arr=new int[]{1,2,3};
         for (int i = 0; i<=arr.length ; i++) {     //访问数组中不存在的最大索引  
            System.out.println(arr[i]);
        }
    }
}

分析:数组初始化后(new后),要获取的数组的索引值,不在该数组的有效索引值之内

报错:Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 3

补充(1):当遍历数组的for循环里漏写了条件判断,也会导致数组索引越界异常;

如下:

public class Test01 {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3, 4, 5};
        for (int i = 0;; i++) {     //漏写了条件   
            System.out.println(arr[i]);
        }
    }
}

报错: Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 5

补充(2):其实,除了数组这个容器会索引越界以外,集合以及String字符串也会报索引越界
集合报索引越界案例如下:

List<Integer> list=new ArrayList<>();
list.add(41);
//System.out.println(list.get(1));报错

报错:Exception in thread “main” java.lang.IndexOutOfBoundsException: Index 1 out-of-bounds for length 1

String报索引越界案例如下:

  String str ="helloworld";
// System.out.println(str.substring(80));报错 

报错:Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: -70

========================================================================================================================================================

NullPointerException 空指针异常

public class Test01 {
    public static void main(String[] args) {
        int[] arr = null;//没有初始化,即没有保存数组地址值  
        System.out.println(arr.length);//空指针
        System.out.println(arr[0]);//空指针
        System.out.println(arr1.toString());//空指针
        System.out.println(arr);//null
    }
}

分析:数组没有进行初始化,不能操作数组;

不管是获取元素还是获取长度,还是调用数组方法都是操作数组,都报空指针异常

报错:Exception in thread “main” java.lang.NullPointerException

补充(1):其实,除了数组这个容器会空指针以外,集合以及String字符串也会报空指针

集合报空指针案例如下:

 List<Integer> list=null;
 System.out.println(list);//null
 //System.out.println(list.size());报错

报错:Exception in thread “main” java.lang.NullPointerException

String报空指针案例如下:

 String str1=null;
 System.out.println(str1);//null
 //System.out.println(str1.length());报错

报错:Exception in thread “main” java.lang.NullPointerException

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值