讓我們來看看這段代碼:
package com;

public class StringTest2


{
public static void main(String[] args)

{
StringBuffer sb = new StringBuffer();
String s = null;
sb.append(s);
System.out.println(sb.length());
StringBuilder sb2 = new StringBuilder();
sb2.append(s);
System.out.println(sb2.length());
}

}

結果會輸出,有人一定會說輸出0.
結果是什么呢?
怎么回事呢,明明添加了一個null值,結果竟然是4.
讓我們來看看append方法的源碼就知道了.
StringBuilder:
// Appends the specified string builder to this sequence.

private StringBuilder append(StringBuilder sb)
{
if (sb == null)
return append("null");
int len = sb.length();
int newcount = count + len;
if (newcount > value.length)
expandCapacity(newcount);
sb.getChars(0, len, value, count);
count = newcount;
return this;
}
StringBuffer的append方法是在它的父類中實現的:

public AbstractStringBuilder append(String str)
{
if (str == null) str = "null";
int len = str.length();
if (len == 0) return this;
int newCount = count + len;
if (newCount > value.length)
expandCapacity(newCount);
str.getChars(0, len, value, count);
count = newCount;
return this;
}

這兩個append方法都有共同的:
if (str == null) str = "null";
int len = str.length();
如果str 是 null,就賦予str = "null" 這個字符串,而再是
null了.
而"null"這個字符串的長度自然是4了.