重载+运算符 javaString
程序员文章站
2022-07-13 16:02:07
...
public class Contenation { public static void main(String[] args) { String str = "Happy"; String str2 = "I" + str + "now" + 21; System.out.println(str2); } } 使用javap -c Contenation反编译得到的JVM字节码: Compiled from "Contenation.java" public class Contenation extends java.lang.Object{ public Contenation(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]); Code: 0: ldc #2; //String Happy 2: astore_1 3: new #3; //class java/lang/StringBuilder 6: dup 7: invokespecial #4; //Method java/lang/StringBuilder."<init>":()V 10: ldc #5; //String I 12: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 15: aload_1 16: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 19: ldc #7; //String now 21: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 24: bipush 21 26: invokevirtual #8; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder; 29: invokevirtual #9; //Method java/lang/StringBuilder.toString:()Ljava/lang/String; 32: astore_2 33: getstatic #10; //Field java/lang/System.out:Ljava/io/PrintStream; 36: aload_2 37: invokevirtual #11; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 40: return } 可以发现,当我们使用+运算符时,他会生成很多临时的String对象,这些对象会在程序结束之后由垃圾回收机制回收;然后调用StringBuilder的append()方法将其拼接在一起,最后调用toString()方法输出。
上一篇: SQL 中的exists关键字
下一篇: Java中的方法调用