Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between casting to String and String.valueOf

Tags:

java

casting

What is the difference between

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

and

Object foo = "something"; String bar = (String) foo; 
like image 711
Dropout Avatar asked May 29 '13 13:05

Dropout


People also ask

What is difference between toString and string valueOf?

String. valueOf will transform a given object that is null to the String "null" , whereas . toString() will throw a NullPointerException . The compiler will use String.

What is the difference between string and toString?

Both these methods are used to convert a string. But yes, there is a difference between them and the main difference is that Convert. Tostring() function handles the NULL while the . ToString() method does not and it throws a NULL reference exception.

What is the use of string valueOf ()?

The java string valueOf() method converts different types of values into string. By the help of string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to string, double to string, object to string and char array to string.

What is valueOf in string?

Java - String valueOf() Method This method returns the string representation of the passed argument. valueOf(boolean b) − Returns the string representation of the boolean argument. valueOf(char c) − Returns the string representation of the char argument.


2 Answers

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

like image 115
Joachim Sauer Avatar answered Oct 03 '22 09:10

Joachim Sauer


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.

like image 35
darijan Avatar answered Oct 03 '22 10:10

darijan