What is the right approach to concatenating a null String in Java?
Asked Answered
S

9

45

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.

Schaumberger answered 5/7, 2014 at 5:58 Comment(5)
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.Misapprehend
How is this not a duplicate nearly 6 years after Stack Overflow was launched?Savdeep
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.Hazelton
@PeterMortensen - I tried to find a dupe, but each search came up with null.Hazelton
Related: Concatenating null strings in JavaImpecunious
E
48

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);
Elizebethelizondo answered 5/7, 2014 at 6:52 Comment(4)
java.util.Objects.toString(obj, default) is the library equivalent of denull(). And good advice overall regarding nulls. +1.Egocentrism
@StuartMarks - It does the same thing as denull. But a special purpose helper method will be more concise.Elizebethelizondo
I named this special purpose helper function "nullToEmpty(...)", but it is semantically identical to "deNull(...)"Fiendish
The OP is apparently looking for a concise way to do the test, and I am pandering to that.Elizebethelizondo
M
40

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

acd

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.
Maurey answered 5/7, 2014 at 11:0 Comment(3)
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)Dodecanese
Nice! However, you could replace the lambda with method reference 'Objects::nonNull'.Gadolinite
@Skiwi Response would be "acd" instead of "abc". Please fix the typoPersecute
P
19
String s = null;
System.out.println("s: " + (s != null ? s : ""));

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

Poach answered 5/7, 2014 at 6:2 Comment(2)
C#: "s: " + (s ?? "")Ledoux
C#: "s: " + s. .NET does not print null. .NET came after Java. Many Java mistakes were not repeated.Mcadams
E
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.

Egocentrism answered 5/7, 2014 at 18:36 Comment(0)
P
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));
Perdurable answered 5/7, 2014 at 6:1 Comment(0)
B
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 "";
    }
}
Biyearly answered 5/7, 2014 at 6:9 Comment(0)
A
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

Annabelle answered 5/7, 2014 at 5:59 Comment(3)
This is not what I am asking for.Schaumberger
@REACHUS I changed the code, use s = s == null ? "" : s; statement to recover from null stringsAnnabelle
@REACHUS Check your problem with the output given?Annabelle
I
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

Incinerator answered 5/7, 2014 at 13:35 Comment(0)
L
0

Consider using org.apache.commons.lang3. There is the Utility class StringUtils. Which provides a bunch of helpful methods for this problem. Just a few examples:

defaultIfBlank(T str, T defaultStr)
      Returns either the passed in CharSequence, or if the CharSequence is whitespace, empty ("") or null, the value of defaultStr.

defaultString(String str)
      Returns either the passed in String, or if the String is null, an empty String ("").
Livy answered 18/6 at 9:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.