什么是空指针异常(java.lang.NullPointerException),是什么原因导致的?

可以使用哪些方法/工具来确定原因,从而阻止异常导致程序过早终止?


当前回答

另一个NullPointerException发生在声明一个对象数组时,然后立即尝试解引用其中的元素。

String[] phrases = new String[10];
String keyPhrase = "Bird";
for(String phrase : phrases) {
    System.out.println(phrase.equals(keyPhrase));
}

如果比较顺序颠倒,则可以避免这种特定的NPE;也就是说,在一个有保证的非空对象上使用.equals。

数组中的所有元素都被初始化为它们共同的初始值;对于任何类型的对象数组,这意味着所有元素都是空的。

在访问或取消引用数组中的元素之前,必须初始化它们。

String[] phrases = new String[] {"The bird", "A bird", "My bird", "Bird"};
String keyPhrase = "Bird";
for(String phrase : phrases) {
    System.out.println(phrase.equals(keyPhrase));
}

其他回答

空指针异常表示您正在使用一个对象而没有初始化它。

例如,下面是一个学生类,将在我们的代码中使用它。

public class Student {

    private int id;

    public int getId() {
        return this.id;
    }

    public setId(int newId) {
        this.id = newId;
    }
}

下面的代码给出了一个空指针异常。

public class School {

    Student student;

    public School() {
        try {
            student.getId();
        }
        catch(Exception e) {
            System.out.println("Null pointer exception");
        }
    }
}

因为你用的是student,但你忘了初始化它 正确代码如下所示:

public class School {

    Student student;

    public School() {
        try {
            student = new Student();
            student.setId(12);
            student.getId();
        }
        catch(Exception e) {
            System.out.println("Null pointer exception");
        }
    }
}

在Java中,您声明的所有变量实际上都是对象(或原语)的“引用”,而不是对象本身。

当您尝试执行一个对象方法时,引用会要求活动对象执行该方法。但是如果引用引用的是NULL (nothing, zero, void, nada),那么就没有办法执行方法。然后运行时通过抛出NullPointerException让你知道这一点。

你的引用是“指向”空,因此“空->指针”。

对象存在于VM内存空间中,访问它的唯一方法是使用该引用。举个例子:

public class Some {
    private int id;
    public int getId(){
        return this.id;
    }
    public setId( int newId ) {
        this.id = newId;
    }
}

在代码的另一个地方:

Some reference = new Some();    // Point to a new object of type Some()
Some otherReference = null;     // Initiallly this points to NULL

reference.setId( 1 );           // Execute setId method, now private var id is 1

System.out.println( reference.getId() ); // Prints 1 to the console

otherReference = reference      // Now they both point to the only object.

reference = null;               // "reference" now point to null.

// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );

// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...

这是一件很重要的事情——当一个对象没有更多的引用时(在上面的例子中,当reference和otherReference都指向null时),那么这个对象是“不可达的”。我们无法使用它,因此该对象已准备好被垃圾收集,在某个时刻,VM将释放该对象使用的内存,并分配另一个内存。

空指针是指不指向任何地方的指针。当你对指针p进行解引用时,你说“给我存储在p中的位置的数据”。当p是一个空指针时,存储在p中的位置是无处不在的,你是在说“给我无处位置的数据”。显然,它不能这样做,所以它抛出一个空指针异常。

一般来说,这是因为某些东西没有正确地初始化。

另一个NullPointerException发生在声明一个对象数组时,然后立即尝试解引用其中的元素。

String[] phrases = new String[10];
String keyPhrase = "Bird";
for(String phrase : phrases) {
    System.out.println(phrase.equals(keyPhrase));
}

如果比较顺序颠倒,则可以避免这种特定的NPE;也就是说,在一个有保证的非空对象上使用.equals。

数组中的所有元素都被初始化为它们共同的初始值;对于任何类型的对象数组,这意味着所有元素都是空的。

在访问或取消引用数组中的元素之前,必须初始化它们。

String[] phrases = new String[] {"The bird", "A bird", "My bird", "Bird"};
String keyPhrase = "Bird";
for(String phrase : phrases) {
    System.out.println(phrase.equals(keyPhrase));
}

当应用程序试图在需要对象的情况下使用null时,将引发空指针异常。这些包括:

调用空对象的实例方法。 访问或修改空对象的字段。 取null的长度,就好像它是一个数组一样。 访问或修改null的槽位,就像它是一个数组一样。 抛出null,就好像它是一个Throwable值。

应用程序应该抛出该类的实例,以指示null对象的其他非法使用。

参考:http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html