Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/24583475/what-is-the-right-approach-to-concatenating-a-null-string-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...