在这段代码片段中创建了多少个对象?
String x = "xyz"; // #1
x.toUpperCase(); /* Line 2 */ #2
String y = x.replace('Y', 'y'); //Will here new object is created or not?
y = y + "abc"; // #3 ?
System.out.println(y);
三。我认为..?
在这段代码片段中创建了多少个对象?
String x = "xyz"; // #1
x.toUpperCase(); /* Line 2 */ #2
String y = x.replace('Y', 'y'); //Will here new object is created or not?
y = y + "abc"; // #3 ?
System.out.println(y);
三。我认为..?
创建了多少对象?
// "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);
此语句返回对同一 String 对象的引用x
:
String y = x.replace('Y', 'y');
查看文档:
如果此 String 对象表示的字符序列中没有出现 oldChar 字符,则返回对该 String 对象的引用。否则,将创建一个新的 String 对象,该对象表示与此 String 对象所表示的字符序列相同的字符序列,除了 oldChar 的每次出现都被 newChar 的出现替换。