Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 279
look4chirag Avatar asked Oct 18 '10 15:10

look4chirag


People also ask

Can we append null to a string in Java?

Core Java bootcamp program with Hands on practice To concatenate null to a string, use the + operator. Let's say the following is our string. String str = "Demo Text"; We will now see how to effortlessly concatenate null to string.

Can StringBuffer append null?

The characters of the StringBuffer argument are appended, in order, to the contents of this StringBuffer, increasing the length of this StringBuffer by the length of the argument. If sb is null, then the four characters "null" are appended to this StringBuffer.

What does StringBuilder append return?

Appends the string representation of the codePoint argument to this sequence. Returns the current capacity. Returns the char value in this sequence at the specified index.

How do you make StringBuilder null?

Use stringBuilderObj. setLength(0) .


2 Answers

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.

like image 158
Anthony Avatar answered Sep 21 '22 03:09

Anthony


I'm not sure why you'd expect it to come out empty, given that the documentation is pretty clear:

If str is null, then the four characters "null" are appended.

Basically you need to either not call append at all if you have a null reference, or switch the value for "".

You could write a method to do this substitution if you find yourself doing it a lot:

public static String nullToEmpty(String text) {     return text == null ? "" : text; } 

Indeed, I've just looked at the Guava documentation and the Strings class has exactly that method (but with a parameter called string instead of text).

like image 31
Jon Skeet Avatar answered Sep 21 '22 03:09

Jon Skeet