Home > Java > javaTutorial > Three methods for converting java objects to String type

Three methods for converting java objects to String type

高洛峰
Release: 2017-01-19 14:15:54
Original
1976 people have browsed it

1. Use Object.toString()
The toString method is a public method of the java.lang.Object object. Any object in Java will inherit the Object object, so generally any object can call the toString method. This is when using this method, often derived classes will override the toString() method in Object.
But when using this method, please note that the Object must not be a null value, otherwise a NullPointerException will be thrown.

2. Use (String)Object
This method is a standard type conversion method that can convert Object to String. However, when using this method, please note that the type to be converted must be convertible to String, otherwise a CalssCastException error will occur.

Object o = new Integer(100);
String string = (String)o;
Copy after login

This program code will cause java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String. Because the Integer type is cast to the String type, it cannot be passed.

3. String.valueOf(Object)
We need to worry about the null problem when using the Object.toString() method above. But there is no need to worry about null values ​​using this method. Because when using String.valueOf(Object), it will determine whether the Object is a null value, and if so, return null. The following is the source code of String.valueOf(Object):

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

From the above we can see two points: First, there is no need to worry about the null problem. Second, it is based on the toString() method.
But be sure to note: when object is null, the value of String.valueOf(object) is the string object: "null", not null! ! !

For more related articles on the three methods of converting Java objects to String types, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template