I am not able to understand the following behavior of StringBuilder when NULL objects are appended to an instance:
public class StringBufferTest {
/**
* @param args
*/
public static void main(String[] args) {
String nullOb = null;
StringBuilder lsb = new StringBuilder();
lsb.append("Hello World");
System.out.println("Length is: " + lsb.length());// Prints 11. Correct
lsb.setLength(0);
System.out.println("Before assigning null" + lsb.length());
lsb.append(nullOb);
System.out.println("Length now is:" + lsb.length()); // Prints 4. ???
}
}
The last print statement does not print 0. Can anyone please help me understand the behavior?
From the StringBuffer API -
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuffer.html#append(java.lang.String)
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.
This should explain the length as 4.
StringBuilder appends "null" when you give it a null reference. It eases debugging. If you want an empty string instead of "null", just test the reference before appending:
if (obj != null) {
builder.append(obj);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With