In many cases we need to convert an object to a string type. There are generally three ways to achieve this: Object.ToString (), (String) Object, String.valueof (object). Here are the three ways to analyze each
First, the use of object.tostring ()
The ToString method is a public method of the Java.lang.Object object. Any object in Java Inherits object objects, so it is generally possible for any object to call the ToString method. This is when this method is used, and often derived classes override the ToString () method in object.
However, when using this method, it is important to ensure that object is not a null value, otherwise the NullPointerException exception will be thrown.
Second, use (String) Object
The method is a standard type conversion method that can convert an object to a string. However, when using this method it is important to note that the type that needs to be converted must be able to be converted to string, otherwise an Calsscastexception exception error occurs.
Copy CodeThe code is as follows:
Object o = new Integer (100);
String string = (String) o;
This program code will appear Java.lang.ClassCastException:java.lang.Integer cannot is cast to java.lang.String. The integer type cannot be passed because it is cast to a string type.
Three, string.valueof (Object)
We need to worry about the null problem when we use the Object.ToString () method above. However, there is no need to worry about null values with this method. Because when you use String.valueof (object), it determines whether the object is a null value, or null if it is. Below is the source code for string.valueof (Object):
Copy CodeThe code is as follows:
public static String valueOf (Object obj) {
return (obj = = null)? "Null": obj.tostring ();
}
From the above we can see two points: first, there is no need to worry about the null problem. The second is that it is based on the ToString () method.
However, it is important to note that when object is null, the value of String.valueof (object) is a string object: "null" instead of null!!!
Three ways to convert a Java object to a string type