且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

转换为String和String.valueOf之间的差异

更新时间:2022-10-15 09:49:39

实际上是一个字符串:

  Object reallyAString =foo; 
String str =(String)reallyAString; //工作。

当对象是其他对象时,它将无法工作:

  Object notAString = new Integer(42); 
String str =(String)notAString; // will throw a ClassCastException

String.valueOf() 将尝试将你传递给它的任何内容转换为 String 。它使用对象的 42 )和对象( new Integer(42) http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString%28%29> toString() ):

  
str = String.valueOf(new Integer(42)); // str将保存42
str = String.valueOf(foo); // str将持有foo
对象nullValue = null;
str = String.valueOf(nullValue); // str将持有null

特别注意最后一个例子:passing null String.valueOf()将返回字符串null p>

What is the difference between

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

and

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() 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"

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