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:
- 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.
- 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.
- 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.