MCMastery MCMastery - 1 month ago 13
Java Question

String.valueOf() vs. Object.toString()

In Java, is there any difference between

String.valueOf(Object)
and
Object.toString()
?
Is there a specific code convention for these?

Answer

According to the Java documentation String.valueOf() returns:

if the argument is null, then a string equal to "null"; 
otherwise, the value of obj.toString() is returned.

So there shouldn't really be a difference except for an additional method invocation.

Also, in case of Object#toString, if the instance is null, a NullPointerException will be thrown, so, arguably, it's less safe.