Search code examples
javastringbuffer

Why the below code is not working (StringBuffer.toString !=null)


I am new to String World ,

I have coded as like below,

StringBuffer buffer=new StringBuffer();
String addressLineOne=null;
buffer.append(addreeLineOne);
if(buffer.toString!=null)
{
 system.out.println("Not NULL");
}

Result:Not Null; (buffer.toString!=null)==true

Eventhough I have append null to buffer ,I am not able to identify it by having NUll check, Code printing Not Null

Why it so?


Solution

  • public StringBuffer append(Object obj)
    

    Appends the string representation of the Object argument.

    The overall effect is exactly as if the argument were converted to a string by the method String.valueOf(Object), and the characters of that string were then appended to this character sequence

    So addressLineOne, would be converted to a String representation, before being appended to the buffer.

    According to JLS, Section 15.18.1.1

    If the reference is null, it is converted to the string "null"

    implicitly, this would happen: String.valueOf(addressLineOne) // would give you a string with value "null" in it.

    Then the characters in the string "null" would each be appended to the buffer.

    Note: On the other hand, new StringBuffer().append(null); would give you an compilation error since the overloaded append() method's argument null would be ambiguous, and String.valueOf(null) would throw a Null Pointer Exception.