You should be careful while appending nulls to StringBuffer as it may result in the unexpected output (if you are not aware how null works with StringBuffer). When you append null to StringBuffer, it actually appends four character string “null” to the buffer instead of an empty string. Let’s take an example to see this behaviour.
public class StringBufferNullExample { public static void main(String args[]) { String str = null; StringBuffer sb = new StringBuffer(); sb.append(str); System.out.println("Length: "+sb.length()); System.out.println("Content: "+sb); } }
Output:
Length: 4 Content: null
As you can see that the length of StringBuffer is 4 after we appended null to it. It is easy to identify and handle null in above example but it may be headache for you when you are not sure about the value of the strings that you are appending to StringBuffer, for example when we are taking the string value from user as an input in that case it depends on the user what he is going to enter. To avoid such issues we must need to do a null check before appending strings to the StringBuffer. This is how we can do this:
if (str != null) sb.append(str);
By doing this you are ensuring that no null values are going to be inserted into the StringBuffer.
Leave a Reply