JAVA面试题02-String和StringBuffer的区别

1.String是final的,不能被继承。
2.String是不可变的,对String的任何拼接,截断操作并不会改变原有String对象,而是重新生成了一些String对象。因此代码中绝对不能在循环中使用字符串拼接操作,这样会导致内存中创建多个String对象。

public final class String
```
 * Strings are constant; their values cannot be changed after they
 * are created. String buffers support mutable strings.
 * Because String objects are immutable they can be shared. For example:
 * <blockquote><pre>
 *     String str = "abc";
 * </pre></blockquote><p>
 * is equivalent to:
 * <blockquote><pre>
 *     char data[] = {'a', 'b', 'c'};
 *     String str = new String(data);
 * </pre></blockquote><p>

3.StringBuffer是可变的,可以动态拼接字符串,适合频繁的字符串拼接操作。
4.StringBuffer是线程安全的。实现线程安全的方式就是简单的加synchronized。因此对同一个StringBuffer对象的操作,都会阻塞在该对象上的其他操作。比如调用length方法一样也会阻塞,因为synchronized 修饰实例方法,锁住的是当前实例对象。

    @Override
    public synchronized StringBuffer append(Object obj) {
        toStringCache = null;
        super.append(String.valueOf(obj));
        return this;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值