Difference between casting to String and String.valueOf

Casting to string only works when the object actually is a string:

Object reallyAString = "foo";
String str = (String) reallyAString; // works.

It won’t work when the object is something else:

Object notAString = new Integer(42);
String str = (String) notAString; // will throw a ClassCastException

String.valueOf() however will try to convert whatever you pass into it to a String. It handles both primitives (42) and objects (new Integer(42), using that object’s toString()):

String str;
str = String.valueOf(new Integer(42)); // str will hold "42"
str = String.valueOf("foo"); // str will hold "foo"
Object nullValue = null;
str = String.valueOf(nullValue); // str will hold "null"

Note especially the last example: passing null to String.valueOf() will return the string "null".

Leave a Comment