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

concatenation, java, string

Solution

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);

Problem

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.

Original source

Related problems