1. object.toString() method
This method should be noted that the object cannot be null, otherwise a NullPointException will be reported, generally do not use this method.
2. String.valueOf(object) method
This method does not have to worry about the problem that the object is null, if it is null
l, will convert it to a "null" string , not null. Pay special attention to this point. "null" and null are not the same concept.
3. (String) (object) method
This method also doesn't have to worry about object being null. However, if object can be converted to a String object. If Object object = 1, then (String)1, a class conversion exception will be reported.
4. ""+object method
This method also doesn't have to worry about object being null. But if object is null, it will return "null" string, same as String.valueOf(object).
The following is a code example:
public class Test {
public static void main(String[] args) {
Object object = null;
System.out.println("(String)null和\"null\"比较的结果为:" + ("null".equals((String)object)));
System.out.println("String.valueOf(null)和\"null\"比较的结果为:" + "null".equals(String.valueOf(object)));
System.out.println("(\"\" + null)和\"null\"比较的结果为:" + "null".equals("" + object));
}
}
operation result:
(String)null compares to "null": false
String.valueOf(null) compares to "null": true
("" + null) compares to "null": true
Way | example | Precautions |
---|---|---|
Object.toString() | Object object = getObject(); System.out.println(object.toString()); |
Pay attention when using it, you must ensure that the object is not a null value, otherwise a NullPointerException will be thrown. |
(String)obj | Object obj = new Object (); String strVal = (String)obj; |
The converted data type must be able to be converted into String type. Therefore, it is best to use instanceof to do a type check to determine whether it can be converted. Otherwise, it is easy to throw CalssCastException. In addition, you need to be especially careful because the syntax check will not report an error when an object defined as Object type is converted to String, which may lead to potential errors. In addition, because null values can be cast to any java class type, ( String)null is also legal. |
String.valueOf(Object) | String.valueOf(object) | Note that when the object is null, the value of String.valueOf(object) is the string "null" instead of null, which is equivalent to displaying the empty flag as data. |