44

I know that the following:

String s = null;
System.out.println("s: " + s);

will output: s: null.

How do I make it output just s: ​?

In my case this is important as I have to concatenate String from 4 values, s1, s2, s3, s4, where each of these values may or may not have null value.

I am asking this question as I don't want to check for every combinations of s1 to s4 (that is, check if these variables are null) or replace "null" with empty String at the end, as I think there may be some better ways to do it.

akash
  • 22,664
  • 11
  • 59
  • 87
syntagma
  • 23,346
  • 16
  • 78
  • 134
  • 3
    An interesting fact (which is not an answer to your question): Given how fussy the Java language can be, it might come as a surprise that string concatenation never throws an exception for `null`, even if you use `+=` on `null` itself. E.g.: `String s = null; s += null;`. After those two statements, `s` becomes the distinctly non-`null` string `"nullnull"`. It's also safe to concatenate an object which is not `null`, but whose `toString()` method is overridden to *return* `null`. In all cases, the concatenation substitutes `"null"` for `null`. – Boann Jul 05 '14 at 07:00
  • How is this not a duplicate nearly 6 years after Stack Overflow was launched? – Peter Mortensen Jul 05 '14 at 11:33
  • There is a difference between a "null String" and a "null reference". A "null String" is `""` and will print as nothing. A null *reference* is not even a String. – Hot Licks Jul 05 '14 at 13:39
  • 10
    @PeterMortensen - I tried to find a dupe, but each search came up with `null`. – Hot Licks Jul 05 '14 at 13:41
  • 2
    Related: [Concatenating null strings in Java](http://stackoverflow.com/q/4260723/500202) – Izkata Jul 05 '14 at 22:41

8 Answers8

47

The most concise solution this is:

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

or maybe create or use a static helper method to do the same; e.g.

System.out.println("s: " + denull(s));

However, this question has the "smell" of an application that is overusing / misusing null. It is better to only use / return a null if it has a specific meaning that is distinct (and needs to be distinct) from the meanings of non-null values.

For example:

  • If these nulls are coming from String attributes that have been default initialized to null, consider explicitly initializing them to "" instead.
  • Don't use null to denote empty arrays or collections.
  • Don't return null when it would be better to throw an exception.
  • Consider using the Null Object Pattern.

Now obviously there are counter-examples to all of these, and sometimes you have to deal with a pre-existing API that gives you nulls ... for whatever reason. However, in my experience it is better to steer clear of using null ... most of the time.

So, in your case, the better approach may be:

String s = "";  /* instead of null */
System.out.println("s: " + s);
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 13
    `java.util.Objects.toString(obj, default)` is the library equivalent of `denull()`. And good advice overall regarding nulls. +1. – Stuart Marks Jul 05 '14 at 18:37
  • 2
    @StuartMarks - It does the same thing as `denull`. But a special purpose helper method will be more concise. – Stephen C Jul 14 '14 at 22:42
  • I named this special purpose helper function "nullToEmpty(...)", but it is semantically identical to "deNull(...)" – Hartmut Pfarr Oct 16 '15 at 11:54
  • The OP is apparently looking for a concise way to do the test, and I am pandering to that. – Stephen C Oct 16 '15 at 18:12
37

You may use the following with Java 8:

String s1 = "a";
String s2 = null;
String s3 = "c";
String s4 = "d";
String concat = Stream.of(s1, s2, s3, s4)
        .filter(s -> s != null)
        .collect(Collectors.joining());

gives

abc

A few things to note:

  • You can turn data structures (lists, etc.) directly into a Stream<String>.
  • You can also give a delimiter when joining the strings together.
skiwi
  • 66,971
  • 31
  • 131
  • 216
  • This is a great way to concatinate Strings! Also notice, that you can use functional interfaces of StringUtils for null checks e.g: .filter(StringUtils::isNotBlank) – Tom Wellbrock Mar 28 '19 at 11:29
  • Nice! However, you could replace the lambda with method reference 'Objects::nonNull'. – abarazal May 06 '20 at 17:39
19
String s = null;
System.out.println("s: " + (s != null ? s : ""));

But what you're really asking for is a null coalescing operator.

David Ehrmann
  • 7,366
  • 2
  • 31
  • 40
11

Another approach is to use java.util.Objects.toString() which was added in Java 7:

String s = null;
System.out.println("s: " + Objects.toString(s, ""));

This works for any object, not just strings, and of course you can supply another default value instead of just the empty string.

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
10

You can use Apache Commons StringUtils.defaultString(String) method, or you can even write your own method that would be just one liner, if you're not using any 3rd party library.

private static String nullToEmptyString(String str) {
    return str == null ? "" : str;
}

and then use it in your sysout as so:

System.out.println("s: " + nullToEmptyString(s));
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
7

You can declare your own method for concatenation:

public static String concat(String... s) 
{//Use varArgs to pass any number of arguments
    if (s!=null) {
       StringBuilder sb = new StringBuilder();
       for(int i=0; i<s.length; i++) {
          sb.append(s[i] == null ? "" : s[i]);
       }
       return sb.toString();
    }
    else {
        return "";
    }
}
akash
  • 22,664
  • 11
  • 59
  • 87
4

Try this

String s = s == null ? "" : s;
System.out.println("s: " + s);

A string variable (here, s) is called null when there is no any objects assigned into the variable. So initialize the variale with a empty string which is ""; Then you can concatenate strings.

If your s variable may be null or not null, Use conditional operator before using it further. Then the variable s is not null further.

This is a sample Code:

    String s1 = "Some Not NULL Text 1 ";
    String s2 = null;
    String s3 = "Some Not NULL Text 2 ";

    s1 = s1 == null ? "" : s1;
    s2 = s2 == null ? "" : s2;
    s3 = s3 == null ? "" : s3;

    System.out.println("s: " + s1 + s2 + s3);

Sample Output:

s: Some Not NULL Text 1 Some Not NULL Text 2

user3717646
  • 436
  • 3
  • 10
1

Two method comes to mind, the first one is not using concatenation but is safest:

public static void substituteNullAndPrint(String format, String nullString, Object... params){
    String[] stringParams = new String[params.length()];
    for(int i=0; i<params.length(); i++){
        if(params[i] == null){
            stringParams[i] = nullString;
        }else{
            stringParams[i] = params[i].toSTring();
        }
    }

    String formattedString = String.format(format, stringParams);
    System.out.println(formattedString);
}

USAGE:
substituteNullAndPrint("s: %s,%s", "", s1, s2);

The second use concatenation but require that your actual string is never contains "null", so it may be utilizable only for very simple cases(Anyway even if you string are never "null" I would never use it):

public static void substituteNullAndPrint(String str){
    str.replace("null", "");
    System.out.println(str);
}

USAGE:
substituteNullAndPrint("s: " + s1);

NOTES:

-Both make use of external utility method since I'm against inlining lot of conditionals.

-This is not tested and I might being confusing c# syntax with Java

Fabio Marcolini
  • 2,315
  • 2
  • 24
  • 30