创建了多少个对象?
// "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