在Java中转换为字符串或使用String.valueOf() [英] Casting to String or using String.valueOf() in Java
问题描述
今天早上,我发现了一个有趣的问题 - 施法对象到字符串检查如果有效,我发现有两种类型的答案。一个是将对象转换为String,另一个是获取该对象的字符串表示(例如,使用String.valueOf()或toString())。我的问题是:什么是最佳实践?它们之间有什么区别?
在我提出这个问题之前,我发现了几个相关的问题,但我没有找到一个答案。请原谅我,如果我错过了重要的一个,希望你不介意指向我的答案。
谢谢你,
如果对象不是字符串,cast将在运行时抛出 ClassCastException
。例如:
对象o = new Object();
String s =(String)o; //其他两个解决方案之间的区别( toString code> vs. String.valueOf
)是一个空对象的情况。 toString
将抛出异常,而 String.valueOf()
将简单地返回null / code>: Object o = null;
String s = String.valueOf(o); // s =null;
String t = o.toString(); // NullPointerException
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,
解决方案 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
这篇关于在Java中转换为字符串或使用String.valueOf()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!