String +的底层实现原理

来个题目,想一下答案应该是什么

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);

新手小白的学习笔记,有什么问题,欢迎指出

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值