Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuffer behavior for NULL objects

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?

like image 718
name_masked Avatar asked Nov 07 '11 18:11

name_masked


2 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 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.

like image 124
Pushkar Avatar answered Oct 04 '22 00:10

Pushkar


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);
}
like image 25
JB Nizet Avatar answered Oct 04 '22 00:10

JB Nizet