上面的回答都很不错。
以下是用javap反编译出来的代码,可以看到“+=”实际导致调用的是 StringBuilder 的相关方法。
"+="的具体执行是这样的:
先创建一个空的StringBuilder,接着调用StringBuilder.append()方法追加左值,再追加右值。
- public static void main(java.lang.String[]);
- Code:
- 0: ldc #2 // String ab
- 2: astore_1
- 3: new #3 // class java/lang/StringBuilder
- 6: dup
- 7: invokespecial #4 // Method java/lang/StringBuilder."<init>":()V
- 10: aload_1
- 11: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
- 14: ldc #6 // String cd
- 16: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
- 19: invokevirtual #7 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
- 22: astore_1
- 23: getstatic #8 // Field java/lang/System.out:Ljava/io/PrintStream;
- 26: aload_1
- 27: invokevirtual #9 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
- 30: return
复制代码 |