2013-04-04 121 views
-2

我是Java的新手,並且有一個與創建字符串有關的問題。創建字符串對象

案例1:

String a = "hello"; 
String b = "world"; 
a = a + b; 
System.out.println(a); 

案例2:

String a; 
String a = "hello"; 
a = new String("world"); 
System.out.println(a); 

我想知道有多少對象在每種情況下被創建。因爲字符串是不可變的,所以一旦賦值給它,那個對象不能被重用(這就是我目前所理解的,如果我錯了,請糾正我)。

如果有人可以用StringBuffer解釋,我會更加高興。謝謝。

+0

這之前的帖子談http://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal – AurA 2013-04-04 03:48:29

+0

您可以輕鬆地獲得很多的教程和文章對這個話題它可以很好地清楚地解釋每件事情。不要問這樣愚蠢的愚蠢的問題,因爲你可以輕鬆地通過在谷歌一擊中得到答案。如果您有任何問題歡迎您提出疑問,請務必妥善處理您的功課,並在做出誠實努力的同時進行。我沒有足夠的信譽分數來投票或關閉它。不要指望餵食勺子。 – 2013-04-04 04:22:39

+0

這個鏈接可能會幫助你:http://www.javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html – 2013-04-04 04:48:26

回答

0

正如你正確地提到,字符串是immutable,下面創建3 string literal objects

String a = "hello"; --first 
String b = "world"; --second 
a = a + b;   --third (the first is now no longer referenced and would be garbage collectioned by JVM) 

在第二種情況下,只有2 string objects創建

String a; 
String a = "hello"; 
a = new String("world"); 

假如你使用的StringBuffer的,而不是字符串第一名,如

StringBuffer a = new StringBuffer("hello"); --first 
String b = "world";       --second 
a.append(b);        --append to the a 
a.append("something more");     --re-append to the a (after creating a temporary string) 

上述只會造成3 objects爲字符串內部級聯到相同的對象,同時使用StringBuffer

+0

我不知道你爲什麼會回答這樣的問題......但工作很好。不要期望OP選擇或選擇這個答案。他會讀'3'和'2',將它們添加到他的作業中,並且永遠不會再被聽到! – jahroy 2013-04-04 04:05:39

+0

@jahroy希望他下次做他的功課:) – Akash 2013-04-04 04:07:05

+0

你鼓勵他不要...... – jahroy 2013-04-04 04:07:32

0

在情況1中,在3個目的,「你好」,「世界」和「HelloWorld」的

在情況2中,兩個對象在字符串池「hello」和「world」中創建。即使世界對象在字符串池中存在,世界對象也會被創建爲新的。

1
Case 1: 

String a = "hello"; -- Creates new String Object 'hello' and a reference to that obj 
String b = "world"; -- Creates new String Object 'world' and b reference to that obj 
a  = a + b;  -- Creates new String Object 'helloworld' and a reference to that obj.Object "hello" is eligible for garbage collection at this point 

So in total 3 String objects got created. 

Case 2: 

String a; -- No string object is created. A String reference is created. 
String a = "hello"; -- A String object "hello" is created and a reference to that 
a  = new String("world"); -- A String object "world" is created and a reference to that. Object "hello" is eligible for garbage collection at this point 


So in total 2 String objects got created 
相關問題