According to the Java documentation, String.valueOf() returns:
if the argument is
null, 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 the case of Object#toString, if the instance is null, a NullPointerException will be thrown, so arguably, it's less safe.
public static void main(String args[]) {
String str = null;
System.out.println(String.valueOf(str)); // This will print a String equal to "null"
System.out.println(str.toString()); // This will throw a NullPointerException
}
Answer from Kuba Rakoczy on Stack Overflowjava - String.valueOf() vs. Object.toString() - Stack Overflow
Cleanest way to check for null on a String?
parseInt() vs valueOf() when to use each?
Integer.parseInt() returns a primitive. valueOf() returns an Integer object. Call the one that matches the return type you need and avoid autoboxing/unboxing.
More on reddit.comConverting a Number to a String
Videos
According to the Java documentation, String.valueOf() returns:
if the argument is
null, 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 the case of Object#toString, if the instance is null, a NullPointerException will be thrown, so arguably, it's less safe.
public static void main(String args[]) {
String str = null;
System.out.println(String.valueOf(str)); // This will print a String equal to "null"
System.out.println(str.toString()); // This will throw a NullPointerException
}
Differences between String.valueOf(Object) and Object.toString() are:
1) If string is null,
String.valueOf(Object) will return "null", whereas Object::toString() will throw a null pointer exception.
public static void main(String args[]){
String str = null;
System.out.println(String.valueOf(str)); // it will print null
System.out.println(str.toString()); // it will throw NullPointerException
}
2) Signature:
valueOf() method of String class is static. whereas toString() method of String class is non static.
The signature or syntax of string's valueOf() method is given below:
public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(char[] c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)
The signature or syntax of string's toString() method is given below:
public String toString()