转换为 String 和 String.valueOf 的区别 [英] Difference between casting to String and String.valueOf

查看:23
本文介绍了转换为 String 和 String.valueOf 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别

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

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

推荐答案

转换为字符串仅在对象实际上是字符串时才有效:

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() 但是会尝试将您传递给它的任何内容转换为 String.它使用该对象的 toString()):

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"

特别注意最后一个例子:将 null 传递给 String.valueOf() 将返回字符串 "null".

Note especially the last example: passing null to String.valueOf() will return the string "null".

这篇关于转换为 String 和 String.valueOf 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆