空指针异常(NullPointerException)
当应用程序试图抛出该类的实例,表示其他对null对象的非法使用:
(1)调用null对象的实例方法;
例如:
1:public class Test {
class A{
public void show(){
System.out.println("A.show");
}
}
public static void main(String[] args){
A a=null;
9: a.show();
}
}
结果
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:9)
(2)访问或修改null对象的的字段
举个栗子:
public class Test {
public static void main(String[] args){
A a=null;
System.out.println(a.name); (4行)
}
}
class A{
public String name="A";
public void show(){
System.out.println(name);
}
}
结果:
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:4)
(3)应用程序应该抛出该类的实例,指示其他对null对象的非法使用
(4)出现这种异常主要是因为程序中的某个对象或变量为空值引起的。