在此代码段中创建了多少个对象?
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);
三。我想..?
答案 0 :(得分:1)
创建了多少个对象?
// "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');
如果字符oldChar未出现在此String对象表示的字符序列中,则返回对此String对象的引用。否则,将创建一个表示字符序列的新String对象与此String对象表示的字符序列相同,只是每次出现的oldChar都被newChar的出现替换。