题目涉及StringBuffer的append方法的源码和StringBuffer构造器的源码
public class IDEADebug {
@Test
public void testStringBuffer(){
String str = null;
StringBuffer sb = new StringBuffer();
sb.append(str);//
/*
源码解析
@Override
public synchronized StringBuffer append(String str) {
toStringCache = null;
super.append(str);
return this;
}
public AbstractStringBuilder append(String str) {
if (str == null)
return appendNull();
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
private AbstractStringBuilder appendNull() {
int c = count;
ensureCapacityInternal(c + 4);
final char[] value = this.value;
value[c++] = 'n';
value[c++] = 'u';
value[c++] = 'l';
value[c++] = 'l';
count = c;
return this;
}
*/
System.out.println(sb.length());//4
System.out.println(sb);//"null"
/*
public StringBuffer(String str) {
super(str.length() + 16);
append(str);
}
*/
StringBuffer sb1 = new StringBuffer(str);//抛异常NullPointerException
System.out.println(sb1);
}
}