对象空指针
  
//理解什么是空指针
public class WhatIsNpe {
  
    public static class User {
  
        private String name;
        private String[] address;
  
        public void print() {
            System.out.println("This is User Class!");
        }
  
        public String readBook() {
            System.out.println("User Read Imooc Escape!");
            return null;
        }
    }
  
    //自定义一个运行时异常
    public static class CustomException extends RuntimeException {}
  
    public static void main(String[] args) {
  
        // 第一种情况: 调用了空对象的实例方法
//        User user = null;
//        user.print();
  
        // 第二种情况: 访问了空对象的属性
//        User user = null;
//        System.out.println(user.name);
  
        // 第三种情况: 当数组是一个空对象的时候, 取它的长度
//        User user = new User();
//        System.out.println(user.address.length);
  
        // 第四种情况: null 当做 Throwable 的值
//        CustomException exception = null;
//        throw exception;
  
        // 第五种情况: 方法的返回值是 null, 调用方直接去使用
        User user = new User();
        System.out.println(user.readBook().contains("MySQL"));
    }
}
变量赋值自动拆箱出现的空指针
方法传参时自动拆箱出现的空指针
基本数据类型优于包装器类型,优先考虑使用基本类型
对于不确定的包装器类型,一定要校验是否是null
对于值为null的包装器类型,赋值为0
//自动拆箱引发的空指针问题
@SuppressWarnings("all")
public class UnboxingNpe {
  
    private static int add(int x, int y) {
        return x + y;
    }
  
    private static boolean compare(long x, long y) {
        return x >= y;
    }
  
    public static void main(String[] args) {
  
        // 1. 变量赋值自动拆箱出现的空指针
        // javac UnboxingNpe.java
        // javap -c UnboxingNpe.class
        Long count = null;
        long count_ = count;
  
        // 2. 方法传参时自动拆箱引发的空指针
//        Integer left = null;
//        Integer right = null;
//        System.out.println(add(left, right));
  
        // 3. 用于大小比较的场景
//        Long left = 10L;
//        Long right = null;
//        System.out.println(compare(left, right));
    }
}
字符串使用equals时出现空指针
对象数组虽然new出来了,但是如果没有初始化,一样会出现空指针
list对象add null不报错,但是addAll不能添加null,否则NPE
//字符串、数组、集合在使用时出现空指针
@SuppressWarnings("all")
public class BasicUsageNpe {
  
    private static boolean stringEquals(String x, String y) {
        return x.equals(y);
    }
  
    public static class User {
        private String name;
    }
  
    public static void main(String[] args) {
  
        // 1. 字符串使用 equals 可能会报空指针错误
//        System.out.println(stringEquals("xyz", null));
//        System.out.println(stringEquals(null, "xyz"));
  
        // 2. 对象数组 new 出来, 但是元素没有初始化
//        User[] users = new User[10];
//        for (int i = 0; i != 10; ++i) {
//            users[i] = new User();
//            users[i].name = "imooc-" + i;
//        }
  
        // 3. List 对象 addAll 传递 null 会抛出空指针
        List<User> users = new ArrayList<User>();
        User user = null;
        List<User> users_ = null;
  
        users.add(user);
        users.addAll(users_);
    }
}