MCMastery MCMastery - 7 months ago 51
Java Question

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

In Java, is there any difference between

Is there a specific code convention for these?


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.