Java StringBuffer

StringBuffer 与 String 的区别、可变字符串操作与常用方法。

Beginner
Key PointsString 不可变、StringBuffer 可变且线程安全、StringBuilder 可变但非线程安全(更快)。单线程优先 StringBuilder。

StringBuffer 与 String 的区别

String allocates on every concatenation; StringBuffer keeps a mutable character array and appends in place, avoiding intermediate objects — ideal for building strings in loops.

Java
public class SBDemo {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");

        sb.append(" World");
        sb.append('!');
        System.out.println(sb);
        System.out.println(sb.length());
        System.out.println(sb.reverse());

        StringBuilder sb2 = new StringBuilder("abc");
        System.out.println(sb2.append(123));
    }
}
Output
Hello World!
12
!dlroW olleH
abc123

StringBuffer 方法

Common methods: append, insert at an index, delete / deleteCharAt, replace a range, reverse, and toString. Each returns the buffer itself, so calls chain.

Java
public class SBMethods {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("abcdef");

        sb.insert(0, ">>");
        System.out.println(sb);

        sb.delete(0, 2);
        System.out.println(sb);

        sb.replace(0, 3, "XYZ");
        System.out.println(sb);

        System.out.println(sb.charAt(0));
        System.out.println(sb.indexOf("Z"));
    }
}
Output
>>abcdef
abcdef
XYZdef
X
2
StringBuffer methods are synchronized, making it slower than StringBuilder in single-threaded code. Use StringBuilder unless the buffer really is shared across threads.

Friends & Partners