While working with StringBuilder you may have come across a strange behaviour of append() method for null values. If you append a null value to the StringBuilder object, it would be stored as a “null” (four character string) in the object instead of no value at all. Let’s take an example to understand what I stated above.
Problem
class AppendNullDemo{
public static void main(String args[]){
// String array with few null elements
String str[] = {" Mango ", null, " Orange ", " Banana ", null};
// Create StringBuilder object
StringBuilder sb = new StringBuilder();
for (String temp: str){
sb.append(temp);
}
// Displaying the output
System.out.println(sb);
}
}
Output:
Mango null Orange Banana null
As you can see that null values are appended as “null” strings in the output, however we prefer to have no values for the null elements. The fix of this issue is provided in the next program.
Solution:
Here is the solution of above issue.
class AdppendNullSolution{
public static void main(String args[]){
// String array with few null elements
String str[] = {" Mango ", null, " Orange ", " Banana ", null};
// Create StringBuilder object
StringBuilder sb = new StringBuilder();
for (String temp: str){
// Append only when the string is not null
if (temp != null)
{
sb.append(temp);
}
}
// Displaying the output
System.out.println(sb);
}
}
Output:
Mango Orange Banana
Issue fixed: Null Strings are eliminated from the output.
The reason of the issue?
The reason is explained in the documentation of the append() method from java docs:public StringBuilder append(String str): Appends the specified string to this character sequence.
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.
Recommended Article: Java StringBuilder class
Leave a Reply