2013-07-30 68 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的出現替換。

相關問題