StringBuffer Behavior for NULL Objects

I cannot understand the following StringBuilder behavior when NULL objects are added 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 someone help me understand the behavior?

+5
source share
3 answers

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 added in order, increasing the length of this sequence by the length of the argument. If str is null, then four null characters are added .

This should explain the length as 4.

+9
source

StringBuilder "null", . . "null", :

if (obj != null) {
    builder.append(obj);
}
+2

No, you set the length to 0; "Before assigning zero" fingerprints 0.

Then you add null, which will be displayed in the buffer as a string "null"that has a length of 4.

+1
source

All Articles