2016-12-27 53 views
-2
String s1=new String("Java"); /* 1st object created */ 
String s2="Tech"; /* 2nd Object */ 
s1+=s2; /* I'm confusing here whether new object created or result stored in previous object */ 

/*共有多少個對象創建的*/在下面的代碼中創建了多少個對象?

+1

只有2.如果發生在編譯上。 – msagala25

+0

在這個問題上有很多SO問題。在發佈之前沒有搜索過嗎?檢查這些:http://stackoverflow.com/questions/47605/string-concatenation-concat-vs-operator http://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal http://stackoverflow.com/questions/26083383/java-string-object-creation – Azodious

+1

字符串是不可變的。他們不會改變。你總是得到一個新的。 –

回答

-1
String s1=new String("Java"); /* 2 objects created as 'new' is used - s1 (holds reference to new String) and string literal "Java" */ 
String s2="Tech"; /* 3rd Object - "Tech", s2 just holds reference to it */ 
s1+=s2; /* 4th Object created, which is concatenation of s1 and s2. s1 holds reference to it. 

所以共有4個創建的對象。

+0

我會認爲's1'持有一個引用,所以它不是一個不同的實例。你能提供一些你說的話嗎? – AxelH

+0

這正是我所提到的 - 「s1(擁有對新字符串的引用)」。你可以有任意數量的對同一個對象的引用,但這個對象在這裏是新的String對象,另一個是字符串文字「Java」。字符串文字存儲在Java中的字符串池中,如果您有另一行:String s3 = new String(「Java」)//則使用相同的字符串文字「Java」對象,因此只會創建一個對象 - new String 。 –

+0

但是你說_2創建爲'new'的對象被使用了_但是我懷疑你可以說Literal是一個Object,因爲我們在'String object'和'String literal'之間做了區別。即使創建的對象是''Java''和'new String(「java」),'s1'不是一個對象,而是一個變量來保存對象的引用;) – AxelH