为什么第一行抛出NullPointerException但第二行没有?

The*_*mon 2 java arrays tostring nullpointerexception

以下代码中的toString方法抛出NullPointerException,但printl打印后调用null.为什么他们没有相同的结果?THL

package exceptionsNullPointer;

public class NPArrays {

    public static void main(String[] args) {
        String[] laces = new String[2];

        // this line throws NullPointerException
        System.out.println(laces[1].toString());

        // this line prints null
        System.out.println(laces[1]);
    }
}
Run Code Online (Sandbox Code Playgroud)

Bob*_*ous 6

因为它laces[1]是对String数组(尚未初始化)成员的完全有效引用.

当创建非基本类型的数组时,其所有成员都默认为null它们,直到它们被赋予实际值.所以参考laces[1]将简单地返回null哪个很好.

但是您的第一行尝试toString在空引用上调用该方法.因为null引用不指向实际的String实例,所以Java唯一能做的就是抛出一个NullPointerException.您不能在null引用(或指针)上调用方法.