How to concatenate string with null without explicitly verifying?

2

When I try to concatenate a String that is actually null with a valid string (eg "a"), I get the value nulla . See the example below:

String a = "a";
String b = null;
System.out.println(b + a);

I wanted the output to be just "a". Is there any way to do this without checking whether String is null ?

    
asked by anonymous 29.06.2016 / 22:45

3 answers

5

You should not try to concatenate a null with a text. I even think java should either prohibit concatenation in this case, or adopt an empty string when it encounters a null (each has pros and cons). As it is not so, the solution is this:

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

See working on ideone .

Obviously you can create a utility method to do this generically and use it whenever you need it.

    
29.06.2016 / 22:54
3

If it is guaranteed that a has a value and only b can be null, you can follow what was answered by Bigown.

If you are not sure and / or need to test a larger number of strings, it may be more interesting to use Optional to check if an object is null. And if this is, return some pre-defined value that will not disturb the concatenation (an empty string maybe ?!):

public static String get(String string){
   return Optional.ofNullable(string).orElse("");
}

Using:

String a = "a", b = null, c = "c";    

get(a) + get(b); // "a"
get(a) + get(b) + get(c); // "ac"
get(b); // ""

IDEONE

    
29.06.2016 / 23:29
2

I believe that instead of setting a String variable to "null" you should set it to "". For example:

public static void main(String[] args) {
    String a = "a";
    String b = "";
    System.out.println(a+b);
}

So it already returns the correct one;

    
13.07.2016 / 22:24