在java中使用null进行类型转换时没有异常 [英] No Exception while type casting with a null in java

查看:134
本文介绍了在java中使用null进行类型转换时没有异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String x = (String) null;

为什么此声明中没有例外?

Why there is no exception in this statement?

String x = null;
System.out.println(x);

打印 null 。但 .toString()方法应抛出空指针异常。

It prints null. But .toString() method should throw a null pointer exception.

推荐答案

您可以将 null 转换为任何引用类型,而不会出现任何异常。

You can cast null to any reference type without getting any exception.

println 方法不会抛出空指针,因为它首先检查对象是否为null。如果为null,则它只打印字符串null。否则它将调用该对象的 toString 方法。

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.

添加更多详细信息:内部打印方法在输入对象上调用 String.valueOf(object)方法。在 valueOf 方法中,此检查有助于避免空指针激活:

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 excpeiton:

return (obj == null) ? "null" : obj.toString();

对于其他的混淆,调用null对象上的任何方法都应抛出空指针异常,如果不是特例。

For rest of your confusion, calling any method on a null object should throw a null pointer exception, if not a special case.

这篇关于在java中使用null进行类型转换时没有异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆