95

What is the difference between

Object foo = "something";
String bar = String.valueOf(foo);

and

Object foo = "something";
String bar = (String) foo;
Matt
  • 14,906
  • 27
  • 99
  • 149
Dropout
  • 13,653
  • 10
  • 56
  • 109

8 Answers8

161

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".

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • 14
    @AdamStelmaszczyk: I doubt there's any that's relevant. *Maybe* casting is slightly faster, but the other differences (null handling, ability to handle other types) are just *significantly* more important than any minor performance difference that there might be. – Joachim Sauer May 29 '13 at 13:38
  • 5
    To push this question a little further, is there any significant difference between calling `String.valueOf()` and `obj.toString()`? (The first one that comes to my mind is that `obj.toString()` will through an exception if `obj` is null.) – Kevin May 29 '13 at 19:08
  • 4
    @Kevin: for reference types (a.k.a "objects") the only difference is what happens with `null`. If you look at the implementation of `String.valueOf()` in your JDK you'll see that all it does for non-null references is to call `toString()`. – Joachim Sauer May 29 '13 at 19:48
  • @JoachimSauer I always thought `String.valueOf()` was more elegant than a cast. But if `String.valueOf()` does everything that casting does, and more, are there any reasons why one would choose to use a cast? Why hasn't it been deprecated? – Shahid M Zubair Nov 12 '14 at 12:59
  • @ShahidMZubair: well, if you know that an object is a `String`, then a cast is the right thing to do. While it is true that `String.valueOf(someString)` has the same effect as `(String) someString` (assuming of course that `someString` actually refers to a `String`), but the latter is more explicit about what it does. Also casts are much more general than `String.valueof()`: they can be done with everything, not just strings (or not just to strings). And last but probably least: a cast is not a method, it's a language feature. so you can't just deprecate it (at least as easily). – Joachim Sauer Nov 12 '14 at 14:48
  • 1
    Tried `str = String.valueOf(null)` in Java 7 Update 80, it throws a `NullPointerException`. – k_rollo Sep 25 '15 at 16:17
  • 2
    @silver: Indeed, I oversimplified. `String.valueOf((Object) null)` will return the String "null". Calling it with a literal `null` will call String#valueOf(char[]) which actually throws a NPE when you pass in `null`. – Joachim Sauer Sep 28 '15 at 11:19
  • Sometimes the fact that String.valueOf doesn't throw an NPE with a non-string object could be a problem because it could bring unpredictable behaviours (the resultant string is not actually the string you are looking for...), sometimes fail fast is better. – George Lords of Castle Nov 27 '20 at 20:01
21

String.valueOf(foo) invokes foo's .toString() method and assigns the result to the the bar. It is null and type safe operation.

Casting will just assign foo to the bar, if the types are matching. Otherwise, the expression will throw a ClassCastException.

darijan
  • 9,725
  • 25
  • 38
5

Casting means that the object needs to be of type String, while String.valueOf() can take other types as well.

tstorms
  • 4,941
  • 1
  • 25
  • 47
5

Both generates same output in case of String.

Casting fails in case of provided object is Not a string.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

String.valueOf method is used to get the String represenation of it's parameter object.

(String) value casts object value to string.

You can use the String.valueOf method to get the String representation of an object without worrying about null references. If you try to cast String on a null reference you would get a NullPointerException.

Syamantak Basu
  • 905
  • 4
  • 10
  • 20
1
final Object obj = null;
final String strValOfObj = String.valueOf(obj);
final String strCastOfObj = (String) obj;
if (strValOfObj == null) System.out.println("strValOfObj is null");
if (strCastOfObj == null) System.out.println("strCastOfObj is null");

Output: strCastOfObj is null

Zaki
  • 6,997
  • 6
  • 37
  • 53
0

The first one i.e, String.valueOf returns a string only if the object is a representable type which is a value type or a String.. Else it throws the exception.

In the latter one, you are directly casting which can fail if the object isn't a string.

Online example.

http://ideone.com/p7AGh5

Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91
0

in String.valueOf(); string as work typecasting all the argument passed in valueof() method convert in String and just like integer.string() convert integer into string only