来个题目,想一下答案应该是什么
String s=null;
s=s+"abc";
System.out.println(s);
果然答案跟我想得不一样,断点调试查看执行原理
public StringBuilder() { //创建一个StringBuilder对象
super(16);
}
AbstractStringBuilder(int capacity) {
value = new char[capacity];
}
调用append拼接第一个String 即s
public StringBuilder append(String str) {
super.append(str);
return this;
}
public AbstractStringBuilder append(String str) {
if (str == null)
return appendNull(); //s为null 执行这个方法
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
将“null”赋值给StringBuilder对象
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;
}
然后再执行append方法拼接"abc"
结果自然为:nullabc
然后将题目改为
String s=new String();
s=s+"abc";
System.out.println(s);
新手小白的学习笔记,有什么问题,欢迎指出