字符串拼接用“+” 使用的是 StringBuilder
Java 语言本身并不支持运算符重载,“+”和“+=”是专门为 String 类重载过的运算符,也是 Java 中仅有的两个重载过的运算符。
public class Test {
public Test() {
}
public static void main(String[] args) {
String s1 = "hello1 ";
String s2 = "hello2 ";
String s3 = "hello3 ";
String s4 = "hello4 ";
(new StringBuilder()).append(s1).append(s2).append(s3).append(s4).toString();
}
}
执行 javap -c Test.class
public static void main(java.lang.String[]);
17: invokespecial #7 // Method java/lang/StringBuilder."<init>":()V
20: aload_1
21: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
24: aload_2
25: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
28: aload_3
29: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
32: aload 4
34: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
37: invokevirtual #9 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
40: astore 5
42: return
可以看出字符串拼接采用的是StringBuilder