MCMastery MCMastery - 1 year ago 109
Java Question

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

In Java, is there any difference between

Is there a specific code convention for these?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download