Home > Java > javaTutorial > body text

Common methods for converting objects to String in Java

零下一度
Release: 2017-07-23 16:54:00
Original
1887 people have browsed it

During development, we often encounter the problem of converting data from collection classes List and Map to String. If we do not handle it well here, we often encounter null pointer exception java.lang.NullPointerException. Here is a summary of commonly used conversions to String. method, and the problem of how to judge null after conversion.


Commonly used methods to convert objects to String in Java:

Method 1: String objStr = (String) obj:

    Forcible type conversion, the object obj is null, and the result is also null, but obj must ensure that its essence is a value of String type, that is, a converted value.

For example, you cannot force conversion (String) 123

Method 2: String objStr = obj.toString():

   When calling the toString method of an object, you must ensure that this class or the parent class has overridden the toString method of the Object class. If the toString method has not been overridden,

The toString method of the Object class will be called by default and return getClass().getName() + '@' + Integer.toHexString(hashCode()),

It is not the actual string representation of obj. At the same time, it must also ensure that the object obj cannot be null, otherwise call toString The method will report a null pointer exception java.lang.NullPointerException.

Method three: String objStr = String.valueOf(obj):

The object obj is null, and the conversion result is the string "null", otherwise, return ## The value of #obj.toString().

Note that if obj is null, the converted value here is already the "null" of the string. Obj == null cannot be used to detect null, nor can apache.commons.lang3

# be used. ##    StringUtils.isBank(CharSequence cs) instead, str.equals("null") should be used.

Already know that obj is of String type:

Use

Method 1

to convert to String. After converting to String, the null condition is: if (objStr != null) Use method 2 with caution

For situations where you don’t know the specific type, You can use
Method 3
, but the null condition of String after conversion is changed to: if (!objStr.equals('null'))

The above is the detailed content of Common methods for converting objects to String in Java. For more information, please follow other related articles on 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