StringBuilder append() and null values

You can do a check on the object before appending it:

sb.append("Value: ");
if (s != null) sb.append(s);
System.out.println(sb);

A key point to make is that null is not the same an an empty String. An empty String is still a String object with associated methods and fields associated with it, where a null pointer is not an object at all.

From the documentation for StringBuilder's append method:

The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument. If str is null, then the four characters "null" are appended.


I'm not sure why you'd expect it to come out empty, given that the documentation is pretty clear:

If str is null, then the four characters "null" are appended.

Basically you need to either not call append at all if you have a null reference, or switch the value for "".

You could write a method to do this substitution if you find yourself doing it a lot:

public static String nullToEmpty(String text) {
    return text == null ? "" : text;
}

Indeed, I've just looked at the Guava documentation and the Strings class has exactly that method (but with a parameter called string instead of text).