創建了多少個對象?
// "xyz" is interned , JVM will create this object and keep it in String pool
String x = "xyz";
// a new String object is created here , x still refers to "xyz"
x.toUpperCase();
// since char literal `Y` is not present in String referenced by x ,
// it returns the same instance referenced by x
String y = x.replace('Y', 'y');
// "abc" was interned and y+"abc" is a new object
y = y + "abc";
System.out.println(y);
此語句返回相同的字符串對象x
參考:
String y = x.replace('Y', 'y');
看那documentation:
如果字符oldChar沒有出現在字符發生由此String對象表示的序列,則返回對此String對象的引用。否則,將創建一個新的String對象,該對象表示與由此String對象表示的字符序列相同的字符序列,但每次出現的oldChar都會被newChar的出現替換。
......第3行怎麼辦? – Doorknob
將語言標籤添加到您的問題。 Java的? –
如果這是Java,則字符串是不可變的,因此將在替換行中創建另一個對象 – Eduardo