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
nullto denote empty arrays or collections. - Don’t return
nullwhen 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);