1. 程式人生 > >Java| Java中String對+的過載

Java| Java中String對+的過載

使用場景一

在Java中是不支援過載運算子的,String的+是java中唯一的一個過載運算子,那麼java使如何實現這個加號的呢?我們先看一段程式碼:

public static void main(String[] args) {
    String s1 = "yves";
    String s2 = s1 + "he";
}

反編譯結果如下:

public static void main(String[] args) {
    String s1 = "yves";
    String s2 = (new StringBuilder(String.
valueOf(s1))).append("he").toString(); }

javap結果如下
javap -c StringPlus.class

Compiled from "StringPlus.java"
public class com.yveshe.StringPlus {
  public com.yveshe.StringPlus();
    Code:
       0: aload_0
       1: invokespecial #8                  // Method java/lang/Object."<init>":()V
       4
: return public static void main(java.lang.String[]); Code: 0: ldc #16 // String yves 2: astore_1 3: new #18 // class java/lang/StringBuilder 6: dup 7: aload_1 8: invokestatic #20 // Method java/lang/String.valueOf:(Ljava/lang/Object;)Ljava/lang/String;
11: invokespecial #26 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V 14: ldc #29 // String he 16: invokevirtual #31 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 19: invokevirtual #35 // Method java/lang/StringBuilder.toString:()Ljava/lang/String; 22: astore_2 23: return }

結論:
看了反編譯之後的程式碼我們發現,其實String對+的支援其實就是使用了StringBuilder以及他的append、toString兩個方法。


使用場景二

String s1 = "yves" + "he";
System.out.println(s1 == "yveshe"); 

輸出結果為true
反編譯程式碼為

String s1 = "yveshe";
System.out.println(s1 == "yveshe");

這裡是由於String s1 = "yves" + "he";在編譯期常量摺疊成String s1 = "yveshe";所以輸出結果為true.