首页 > 技术文章 > Java复现NullPointerException异常

chengho 2020-12-11 17:22 原文

NullPointerException,空指针异常,使用空对象(null)调用类属性或方法

例如:

public class TestNullPointer {
    public static void main(String[] args) {
        TestNullPointer t = new TestNullPointer();

        //使用null作为方法的参数,调用String类的方法
        t.func(null);
    }

    public void func(String str){
        str.equals("");
    }
}

输出:

Exception in thread "main" java.lang.NullPointerException
    at test2.TestNullPointer.func(TestNullPointer.java:11)
    at test2.TestNullPointer.main(TestNullPointer.java:7)

 

推荐阅读