2013-04-04 119 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 
相关问题