Casting to String or using String.valueOf() in Java [duplicate]

Deadly 提交于 2019-12-24 13:24:15

问题


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,


回答1:


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


来源:https://stackoverflow.com/questions/17029719/casting-to-string-or-using-string-valueof-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!