In many cases, we need to convert an object to the String type. Generally, three methods can be implemented: Object. toString (), (String) Object, and String. valueOf (Object ). The following three methods are analyzed one by one:
1. Use Object. toString ()
The toString method is a public method of the java. lang. Object. Any Object in java will inherit the Object, so generally any Object can call the toString method. When this method is used, the common derived class will overwrite the toString () method in the Object.
However, when using this method, you must ensure that the Object is not a null value. Otherwise, an NullPointerException will be thrown.
Ii. Use (String) Object
This method is a standard type conversion method that can convert an Object to a String. However, when using this method, you must note that the type to be converted must be converted to String. Otherwise, a CalssCastException error occurs.
[Java]
Object o = new Integer (100 );
String string = (String) o;
Java. lang. ClassCastException: java. lang. Integer cannot be cast to java. lang. String. The Integer type cannot be forcibly converted to the String type.
Iii. String. valueOf (Object)
We have to worry about null when using the Object. toString () method. However, you do not need to worry about the null value when using this method. When String. valueOf (Object) is used, it determines whether the Object is null. If yes, null is returned. The following is the source code of String. valueOf (Object:
[Java]
Public static String valueOf (Object obj ){
Return (obj = null )? "Null": obj. toString ();
}
We can see from the above two points: first, there is no need to worry about null. Second, it is based on the toString () method.
Note: When the object is null, the value of String. valueOf (object) is a String object: "null", not null !!!
Author: chenssychenssy