Analysis of three methods for String type conversion

Source: Internet
Author: User

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

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.