Get empty string when null

If alternative way, Guava provides Strings.nullToEmpty(String).

Source code

String str = null;
str = Strings.nullToEmpty(str);
System.out.println("String length : " + str.length());

Result

0

For java 8 you can use Optional approach:

Optional.ofNullable(gearBox).orElse("");
Optional.ofNullable(id).orElse("");

You can use Objects.toString() (standard in Java 7):

Objects.toString(gearBox, "")

Objects.toString(id, "")

From the linked documentation:

public static String toString(Object o, String nullDefault)

Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.

Parameters:
o - an object
nullDefault - string to return if the first argument is null

Returns:
the result of calling toString on the first argument if it is not null and the second argument otherwise.

See Also:
toString(Object)


If you don't mind using Apache commons, they have a StringUtils.defaultString(String str) that does this.

Returns either the passed in String, or if the String is null, an empty String ("").

If you also want to get rid of "null", you can do:

StringUtils.defaultString(str).replaceAll("^null$", "")

or to ignore case:

StringUtils.defaultString(str).replaceAll("^(?i)null$", "")

Tags:

Java

Guava