+ 1
Object into a String ?
which of the following is the best approach for converting an Object into a String ? String.valueOf(); .toString(); (String) please give explanation!
1 Answer
+ 10
For String.valueOf() vs .toString(), there should be not much a difference when it comes to Object.
https://stackoverflow.com/questions/27465731/string-valueof-vs-object-tostring
However, if instance of class Object is null, toString() will throw NullPointerException, while String.ValueOf() will just return null.
As for casting Object to String via (String), you *can* do so as long as you know what you are doing. You are basically telling the compiler that this instance of class Object is a String, and you can safely cast it to String at runtime. If the instance of the class is actually not a String, ClassCastException will be thrown.
The best approach after taking everything into consideration (including the link) would be String.valueOf().