1、三者之间的区别
String: 字符串常量,值一旦被设定无法更改
StringBuilder:字符串变量,但是线程不安全,效率高于StringBuffer
StringBuffer:字符串变量,线程安全的
2、例子解释该怎么用
public class StringTest {
public static void main(String[] args) {
// 无变量的字符串拼接
String s = "aa"+"bb"+"cc";
System.out.println(s);
// 有变量的字符串拼接
String g = "aa"+s+3;
System.out.println(g);
// 循环中使用字符串拼接
String a = "1";
for (int i = 1; i < 10; i++) {
a = a + i;
}
System.out.println(a);
// 循环外定义StringBuilder
StringBuilder b = new StringBuilder();
for (int i = 1; i < 10; i++) {
b.append(i);
}
System.out.println(b);
}
}
(1)无变量的字符串拼接,在编译期间值都确定了,所以 javac 工具帮我们把它直接编译成一个字符常量。
(2)有变量的字符串拼接,在编译期间变量的值无法确定,所以运行期间会生成一个StringBuilder 对象。
(3)循环中使用字符串拼接,循环内,每循环一次就会产生一个新的 StringBuilder 对象,对资源有一定的损耗。
(4)循环外使用 StringBuilder,循环内再执行 append() 方法拼接字符串,只会成一个 StringBuilder 对象。
因此,对于有循环的字符串拼接操作,建议使用 StringBuilder 和 StringBuffer,对性能会有一定的提升。
3、总结
String:适用于少量的字符串操作的情况
StringBuilder:适用于单线程下在针对于字符串变量进行多次变化的情况
StringBuffer:适用多线程下在针对于字符串变量进行多次变化的情况