Reputation: 9794
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?
Upvotes: 5
Views: 14938
Reputation: 7580
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.
Upvotes: 9
Reputation: 691755
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);
}
Upvotes: 2
Reputation: 160191
No, you set the length to 0; the "Before assigning null" prints 0.
Then you append null
, which will appear in the buffer as the string "null"
, which has length four.
Upvotes: 1