String.valueOf()与Object.toString() [英] String.valueOf() vs. Object.toString()
问题描述
在Java中, String.valueOf(Object)
和 Object.toString()
之间有什么区别吗?
这些是否有特定的代码约定?
In Java, is there any difference between String.valueOf(Object)
and Object.toString()
?
Is there a specific code convention for these?
推荐答案
根据 Java文档, String.valueOf()
返回:
如果参数是
null
,然后是一个等于null的字符串
;否则,返回obj.toString()
的值。
if the argument is
null
, then a string equal to"null"
; otherwise, the value ofobj.toString()
is returned.
所以除了额外的方法调用之外,应该没有什么区别。
So there shouldn't really be a difference except for an additional method invocation.
此外,在的情况下,对象#toString
,如果实例是 null
,将抛出 NullPointerException
,所以可以说,它不那么安全。
Also, in the case of Object#toString
, if the instance is null
, a NullPointerException
will be thrown, so arguably, it's less safe.
public static void main(String args[]) {
String str = null;
System.out.println(String.valueOf(str)); // This will print a String equal to "null"
System.out.println(str.toString()); // This will throw a NullPointerException
}
这篇关于String.valueOf()与Object.toString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!