In Java, is there any difference between String.valueOf(Object)
and Object.toString()
?
Is there a specific code convention for these?
Java – String.valueOf() vs. Object.toString()
javastring
javastring
In Java, is there any difference between String.valueOf(Object)
and Object.toString()
?
Is there a specific code convention for these?
Best Answer
According to the Java documentation,
String.valueOf()
returns:So there shouldn't really be a difference except for an additional method invocation.
Also, in the case of
Object#toString
, if the instance isnull
, aNullPointerException
will be thrown, so arguably, it's less safe.