What is the difference between
Object foo = "something";
String bar = String.valueOf(foo);
and
Object foo = "something";
String bar = (String) foo;
Thanks!
Casting to string only works when the object actually is a string:
It won't work when the object is something else:
Note especially the last example: passing |
|||||||||||||||||
|
Casting will just assign foo to the bar, since the types are matching. Otherwise, the expression would throw a |
|||||
|
Casting means that the object needs to be of type String, while |
|||
|
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. |
|||
|
Both generates same output in case of
|
|||||
|
The first one i.e, In the latter one, you are directly casting which can fail if the object isn't a string. Online example. |
|||
|
Object foo = new Date();
– johnchen902 May 29 at 13:32