2013-07-30 37 views
-6

在此代码段中创建了多少对象?String类replace()方法

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

......第3行怎么办? – Doorknob

+0

将语言标签添加到您的问题。 Java的? –

+0

如果这是Java,则字符串是不可变的,因此将在替换行中创建另一个对象 – Eduardo

回答

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); 

此语句返回相同的字符串对象x参考:

String y = x.replace('Y', 'y'); 

看那documentation

如果字符oldChar没有出现在字符发生由此String对象表示的序列,则返回对此String对象的引用。否则,将创建一个新的String对象,该对象表示与由此String对象表示的字符序列相同的字符序列,但每次出现的oldChar都会被newChar的出现替换。

相关问题