Three ways to convert a String from a Java object

  • 2020-04-01 02:33:37
  • OfStack

I. Object. ToString ()
The toString method is a public method of the java.lang.object Object. In Java any Object inherits an Object Object, so in general any Object can call the method toString. This is used when a derived class overrides the toString() method in Object.
Note, however, that when using this method, you must ensure that the Object is not a null value, or you will throw a NullPointerException exception.

2. Use (String)Object
  This method is a standard type conversion method that converts an Object to a String. However, when using this method, it is important to note that the type to be converted must be able to be converted to String, otherwise a CalssCastException exception will occur.


Object o = new Integer(100);
String string = (String)o;

This code will be Java. Lang. ClassCastException: Java. Lang. Integer always be cast to Java. Lang. String. Unable to cast Integer to String.

Third, the String. The valueOf (Object)
Above, we need to worry about null when using the object.tostring () method. But you don't have to worry about null values with this method. Because when string.valueof (Object) is used, it determines whether the Object is null, and returns null if it is. The following is the String. ValueOf (Object) source code:


public static String valueOf(Object obj) {
     return (obj == null) ? "null" : obj.toString(); 
}

From the above, we can see two things: first, there is no need to worry about the null problem. The second is that it's based on the toString() method.
But be aware that when object is null, the valueOf string.valueof (object) is a String object: "null", not null!!


Related articles: