为什么第一行抛出 NullPointerException 但第二行没有?
Why does the first line throw NullPointerException but second does not?
以下代码中的 toString 方法抛出 NullPointerException,但之后的 println 调用打印出 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]);
}
}
因为 laces[1]
是对 String
数组(尚未初始化)成员的完全有效引用。
创建非基本类型的数组时,其所有成员默认为 null
,直到它们被赋予实际值。所以引用 laces[1]
将简单地 return null
这很好。
但是您的第一行尝试在空引用上调用 toString
方法。因为空引用不指向实际的 String
实例,所以 Java 唯一能做的就是抛出一个 NullPointerException
。您不能在 null
引用(或指针)上调用方法。
laces[1]
为空,因为您尚未为其分配非空引用。这意味着在第一种情况下,您不能取消引用它来调用 toString()
,否则您将得到 NullPointerException
.
然而,在第二种情况下:引用PrintStream.print(String)
的javadoc:
If the argument is null
then the string "null"
is printed.
如前所述,laces[1] 是 null
,因此您不能对其调用任何方法。
您可以使用 Objects.toString
来获得空安全的字符串表示形式,例如 System.out.println(Objects.toString(laces[1]));
以下代码中的 toString 方法抛出 NullPointerException,但之后的 println 调用打印出 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]);
}
}
因为 laces[1]
是对 String
数组(尚未初始化)成员的完全有效引用。
创建非基本类型的数组时,其所有成员默认为 null
,直到它们被赋予实际值。所以引用 laces[1]
将简单地 return null
这很好。
但是您的第一行尝试在空引用上调用 toString
方法。因为空引用不指向实际的 String
实例,所以 Java 唯一能做的就是抛出一个 NullPointerException
。您不能在 null
引用(或指针)上调用方法。
laces[1]
为空,因为您尚未为其分配非空引用。这意味着在第一种情况下,您不能取消引用它来调用 toString()
,否则您将得到 NullPointerException
.
然而,在第二种情况下:引用PrintStream.print(String)
的javadoc:
If the argument is
null
then the string"null"
is printed.
如前所述,laces[1] 是 null
,因此您不能对其调用任何方法。
您可以使用 Objects.toString
来获得空安全的字符串表示形式,例如 System.out.println(Objects.toString(laces[1]));