Any easy way to check for null before converting an object to a string

I always write

Object o; if (o!=null) String s = o.toString(); 

If there is an easy way to handle this case?

+42
java null
Apr 02 2018-11-11T00:
source share
8 answers

ObjectUtils.toString(object) from commons-lang. There is actually one line in the code:

 return obj == null ? "" : obj.toString(); 

Just one note - use toString() for debugging and logging only. Do not rely on toString() format.

+35
Apr 02 2018-11-11T00:
source share

The static valueOf method in the String class will perform a null check and return "null" if the object is null :

 String stringRepresentation = String.valueOf(o); 
+65
Apr 2 '11 at 9:00
source share

Try Objects.toString(Object o, String nullDefault)

Example:

 import java.util.Objects; Object o1 = null; Object o2 = "aString"; String s; s = Objects.toString(o1, "isNull"); // returns "isNull" s = Objects.toString(o2, "isNull"); // returns "aString" 
+47
03 Dec
source share

Updated answer of Bojo and Jan-59 for reference:

ObjectUtils.toString(object) from commons-lang. There is actually one line in the code:

 return obj == null ? "" : obj.toString(); 

However, this method in Apache Commons is now deprecated after release 3.2 (commons / lang3). Their goal was to remove all methods available in Jdk7. This method has been replaced by java.util.Objects.toString(Object) in Java 7 and is likely to be removed in future versions. After some discussion, they have not deleted it yet (currently in 3.4), and it is still available as an obsolete method.

Note that the specified java 7+ method returns "null" for null references, while this method also returns an empty string. To keep using behavior

 java.util.Objects.toString(myObject, "") 
+4
Jun 23 '15 at 8:06
source share

String.valueOf(o) returns the string "null" if o is null.

Another could be String s = o == null? "default" : o.toString() String s = o == null? "default" : o.toString()

+3
Apr 02 2018-11-11T00:
source share

You can use java 8 optional as follows:

 String s = Optional.ofNullable(o).map(Object::toString).orElse("null"); 
+3
Jul 12 '16 at 8:40
source share

It looks like you want to get a string when o is not NULL. But I am confused that if you code like yours, you cannot access the s variable (you know s in the if help).

+2
Apr 02 2018-11-11T00:
source share

Depending on what you want, this is null , but you can just do it

 Object o = String s = ""+o; 

This is the default behavior for println and adding lines, etc.

+1
Apr 02 2018-11-11T00:
source share



All Articles