I have a list of String
s, and I want to concatenate them with spaces in between. So I\'m using StringBuilder
. Now if any of the String
s ar
With Java 8 you could also use the java.util.Optional class to provide a default value:
System.out.println(sb.append("Value: ").append(Optional.ofNullable(s).orElse("")));
Null check as @Shynthriir has mentioned is the simplest most efficient way (AFAIK) to get around the problem.
I would however strongly recommend initiating strings to an empty string String str = "";
instead, which would save you a lot of headache in a more complex programming effort.
For my purpose, I needed to generalize Answer #2 a little bit. Here is the same function, taking Object as argument, instead of String:
private String nullToEmpty(Object obj) {
return obj == null ? "" : obj.toString();
}
import java.util.Objects;
...
sb.append(Objects.toString(s, ""));
Uses Java internal utils, no external libs are needed. toString
takes String, checks if it is null
and if it is null
, then returns specified default value, in this case ""
(empty string), if it is not null
it returns provided string.
In one line you can do:
System.out.println(sb.append("Value: ").append((s==null)?"":s));
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
).