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

你可能感兴趣的:(面试宝典)