Three ways to convert Java to String, among which String.valueOf should be used with caution

When casting an object to a String type, if the object is null, a NullPointerException will be thrown. To prevent this from happening, some methods available in Java can be used:

  1. Use the string concatenation ""(recommend
Object obj = null;
String str = obj + "";

If obj is null, obj + "" will return an empty string and no NullPointerException will be thrown.

  1. Use the String.valueOf(Object obj) method (Not recommended
Object obj = null;
String str = String.valueOf(obj);

If obj is null, the String.valueOf(obj) method will convert it to the string "null" and no NullPointerException will be thrown.

  1. Use Objects.toString(Object obj, String defaultValue) method (recommend
Object obj = null;
String str = Objects.toString(obj, "");

The Objects.toString(Object obj, String defaultValue) method can convert obj to a string, and can set a default value defaultValue. If obj is null, the value of the defaultValue parameter will be returned, here we set defaultValue to an empty string "".

Through the above three methods, we can prevent NullPointerException from occurring when Object is forced to String.

Guess you like

Origin blog.csdn.net/weixin_43933728/article/details/131228369