Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - StringBuilder append() and null values

I have a list of Strings, and I want to concatenate them with spaces in between. So I'm using StringBuilder. Now if any of the Strings are null, they get stored in the StringBuilder literally as 'null'. Here is a small program to illustrate the issue:

public static void main(String ss[]) {
    StringBuilder sb = new StringBuilder();

    String s;
    s = null;

    System.out.println(sb.append("Value: ").append(s));
}

I'd expect the output to be "Value: " but it comes out as "Value: null"

Is there a way around this problem?

question from:https://stackoverflow.com/questions/3960712/stringbuilder-append-and-null-values

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

1 Answer

0 votes
by (71.8m points)

You can do a check on the object before appending it:

sb.append("Value: ");
if (s != null) sb.append(s);
System.out.println(sb);

A key point to make is that null is not the same an an empty String. An empty String is still a String object with associated methods and fields associated with it, where a null pointer is not an object at all.

From the documentation for StringBuilder's append method:

The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument. If str is null, then the four characters "null" are appended.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...