public class TestStringBuffer{
public static void main(String[] args){
StringBuffer sb = new StringBuffer();
sb.append("abc");
sb.append("123");
System.out.println("sb = " + sb);
sb.insert(3, "--");
System.out.println("sb = " + sb);
sb.delete(2,6);
System.out.println("sb = " + sb);
sb.reverse();
System.out.println("sb = " + sb);
String str = sb.toString(); // 13行
System.out.printf("str = " + str);
}
}
阿神2017-05-17 10:06:19
StringBuffer
String
How can this be the same type?StringBuffer
在做字符串连接 + 或者输出的时候
会隐式执行toString()
转化为String
Line 13 is the displayed execution sb.toString()
将sb
转换为 String
天蓬老师2017-05-17 10:06:19
StringBuffer: String buffer
String: String
When modifying a string, you need to use the StringBuffer and StringBuilder classes.
Different from the String class, objects of the StringBuffer and StringBuilder classes can be modified multiple times without generating new unused objects .
The StringBuilder class was proposed in Java 5. The biggest difference between it and StringBuffer is that the methods of StringBuilder are not thread-safe (cannot be accessed synchronously).
Since StringBuilder has a speed advantage compared to StringBuffer, it is recommended to use the StringBuilder class in most cases. However, in cases where the application requires thread safety, the StringBuffer class must be used.