3

If I have

String a = null;
System.out.println(a);

I'll get

null

Is there an elegant way to change this an empty string?

I could do:

if (a == null){
a="";
}

The context is that I'll be producing a string of the form:

String myString = a + "\n" + b + "\n" + c;

But I'm wondering if there's a nicer solution.

dwjohnston
  • 11,163
  • 32
  • 99
  • 194
  • 2
    Could you not just say `String a = "" `? The String would drop its pointer at null, and then point to an empty string. – Ungeheuer Apr 09 '15 at 03:56

4 Answers4

13

You could try it like this using the ternary operator.

System.out.println(a == null ? "" : a);

Alernatively, you can use the Commons Lang3 function defaultString() as suggested by chrylis,

System.out.println(StringUtils.defaultString(a));
shauryachats
  • 9,975
  • 4
  • 35
  • 48
6

I would factor out a utility method that captures the intention, which improves readability and allows easy reuse:

public static String blankIfNull(String s) {
    return s == null ? "" : s;
}

Then use that when needed:

System.out.println(blankIfNull(a));
Bohemian
  • 412,405
  • 93
  • 575
  • 722
4

Apache commons lang3 has a function that will do this.

import org.apache.commons.lang3.StringUtils;

a = null;
System.out.println(StringUtils.defaultString(a));
dwjohnston
  • 11,163
  • 32
  • 99
  • 194
2

You could write a varargs method

public static String concat(String... arr) {
    StringBuilder sb = new StringBuilder();
    for (String s : arr)
        if (s != null)
            sb.append(s);
    return sb.toString();
}

Then you can do

String myString = concat(a, "\n", b, "\n", c);
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116