Java Object Conversion String type three methods _java

Source: Internet
Author: User
Tags object object

First, the use of object.tostring ()
The ToString method is a public method of the Java.lang.Object object. Any object in Java inherits the object, so it is generally possible for any object to invoke the method of ToString. This is the way in which a common derived class overwrites the ToString () method in object.
However, when using this method, be aware that object is not a null value, or you will throw a NullPointerException exception.

Second, the use of (String) Object
The method is a standard type conversion method that converts object to string. However, in 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 a Calsscastexception exception error occurs.

Copy Code code as follows:

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

This program code will appear Java.lang.ClassCastException:java.lang.Integer cannot be cast to java.lang.String. Because the integer type is cast to a string type, it cannot be passed.

Iii. string.valueof (Object)
We need to worry about the null problem when we use the Object.ToString () method. However, you do not need to worry about the null value problem with this method. Because when string.valueof (object) is used, it determines whether object is a null value and, if so, returns NULL. The following is the source code for string.valueof (Object):

Copy Code code 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!!!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.