Vic*_*cky 209 java nullpointerexception typecasting-operator
String x = (String) null;
Run Code Online (Sandbox Code Playgroud)
为什么这句话中没有例外?
String x = null;
System.out.println(x);
Run Code Online (Sandbox Code Playgroud)
It prints null
. But .toString()
method should throw a null pointer exception.
Jun*_*san 295
You can cast null
to any reference type without getting any exception.
The println
method does not throw null pointer because it first checks whether the object is null or not. If null then it simply prints the string "null"
. Otherwise it will call the toString
method of that object.
Adding more details: Internally print methods call String.valueOf(object)
method on the input object. And in valueOf
method, this check helps to avoid null pointer exception:
return (obj == null) ? "null" : obj.toString();
Run Code Online (Sandbox Code Playgroud)
For rest of your confusion, calling any method on a null object should throw a null pointer exception, if not a special case.
Pet*_*rey 141
You can cast null
to any reference type. You can also call methods which handle a null
as an argument, e.g. System.out.println(Object)
does, but you cannot reference a null
value and call a method on it.
BTW There is a tricky situation where it appears you can call static methods on null
values.
Thread t = null;
t.yield(); // Calls static method Thread.yield() so this runs fine.
Run Code Online (Sandbox Code Playgroud)
And*_*nek 35
This is by design. You can cast null
to any reference type. Otherwise you wouldn't be able to assign it to reference variables.
Mew*_*wel 21
对于方法重载的后续构造需要转换空值,并且如果将null传递给这些重载方法,则编译器不知道如何消除歧义,因此在这些情况下我们需要对类型进行类型转换:
class A {
public void foo(Long l) {
// do something with l
}
public void foo(String s) {
// do something with s
}
}
new A().foo((String)null);
new A().foo((Long)null);
Run Code Online (Sandbox Code Playgroud)
否则你无法调用所需的方法.
Println(Object)
用途 String.valueOf()
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Run Code Online (Sandbox Code Playgroud)
Print(String)
空检查。
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
Run Code Online (Sandbox Code Playgroud)
这里的许多答案已经提到
您可以将 null 强制转换为任何引用类型
和
如果参数为空,则字符串等于“空”
我想知道它在哪里指定并查找了 Java 规范:
始终可以将空引用分配或强制转换为任何引用类型(第 5.2 节、第 5.3 节、第 5.5 节)。
如果引用为空,则将其转换为字符串“空”(四个 ASCII 字符 n、u、l、l)。
归档时间: |
|
查看次数: |
126445 次 |
最近记录: |