String a = "hello";
String b = "world";
String c = "ok";
String d = "is";
String result = a+b+c+d;
問:共產生多少個對象?
答:
現在的編譯器早就對這些代碼作了優化,編譯成如下:
String a = "hello";
String b = "world";
String c = "ok";
String d = "is";
String result = new StringBuffer().append(a),append(b),append(c).append(d).toString();
因此產生了6個對象,其中5個字符串對象,一個StringBuffer臨時對象。