Any simple way to test null before convert an object to string

I always write

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

If there simple way to handle this case?


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

String stringRepresentation = String.valueOf(o);

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"

ObjectUtils.toString(object) from commons-lang. The code there is actually one line:

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

Just one note - use toString() only for debug and logging. Don't rely on the format of toString().


Updated answer of Bozho and January-59 for reference:

ObjectUtils.toString(object) from commons-lang. The code there is actually one line:

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

However this method in Apache Commons is now deprecated since release 3.2 (commons/lang3). Their goal here was to remove all the methods that are available in Jdk7. The method has been replaced by java.util.Objects.toString(Object) in Java 7 and will probably be removed in future releases. After some discussion they did not remove it yet (currently in 3.4) and it is still available as a deprecated method.

Note however that said java 7+ method will return "null" for null references, while this method returns and empty String. To preserve behavior use

java.util.Objects.toString(myObject, "")

import java.util.Objects;
Objects.toString(object, "")

Simple and 0 runtime exception :)