1

This morning I found an interesting question --- cast object to string check if valid and I found there are two types of answers. One is to cast an object to String, the other one is to get the string representation of that object instead (eg. using String.valueOf() or toString()). My questions are: what is the best practice? what is the difference between them?

Before I asked this questions, I found several existing questions which are relevant, but I didn't find one which answers my question. Please forgive me if I missed the important one and hope you don't mind pointing me to the answers.

Thank you,

Community
  • 1
  • 1
keelar
  • 5,814
  • 7
  • 40
  • 79
  • 1
    IMO I would go the secure way and use `instanceof`. Executing `toString` in a `String` object seems redundant and if the object reference is not a `String` and haven't overridden the `toString` method it could lead to unknown behavior. – Luiggi Mendoza Jun 10 '13 at 17:41
  • @LuiggiMendoza, thank you for your fast response. Can I further know why it is regarded as a more secure way? Or why is the valueOf function is insecure? – keelar Jun 10 '13 at 17:42

1 Answers1

12

If the Object is not a String, a cast will throw a ClassCastException at runtime. For example:

Object o = new Object();
String s = (String) o; //Exception here

The difference between the other two solutions (toString vs. String.valueOf) is in the case of a null object. toString will throw an exception whereas String.valueOf() will simply return "null":

Object o = null;
String s = String.valueOf(o); //s = "null";
String t = o.toString(); //NullPointerException
assylias
  • 321,522
  • 82
  • 660
  • 783
  • Thank you very much for you answer. I am sorry that I can't vote up for now as I have reached the daily limit, I will certainly vote up once I can. So in your answer you tells the difference between casting and using functions. Can I know which one (casting or converting) is better in practice? or the answer depends on the use cases? Thank you. – keelar Jun 10 '13 at 17:46
  • 2
    @keelar If you are 100% sure that you have a String, casting is fine (for example after an `if(o instanceof String)` check). If you don't know and just want a String representation of some random object, you should use toString or String.valueOf (depending on the desired behaviour in case of a null string). – assylias Jun 10 '13 at 17:48