According to the Java documentation,
String.valueOf()
returns:if the argument isnull
, 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.
Also, in case of
Object#toString
, if the instance is null
, a NullPointerException
will be thrown, so, arguably, it's less safe.
If string is null,
String.valueOf(Object
) will prints null whereas Object.toString()
will throw null pointer exception.public static void main(String args[]){
String str = null;System.out.println(String.valueOf(str)); // it will prints nullSystem.out.println(str.toString()); // it will throw NullPointer Exception}
Comments
Post a Comment