字符串对象创建

时间:2013-04-04 03:42:01

标签: java string object immutability stringbuffer

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

我想知道在每种情况下创建了多少个对象。因为String是不可变的,所以一旦赋值给它就不能重用该对象(这就是我目前所理解的,如果我错了,请纠正我。)

如果有人能用StringBuffer解释相同的话,我会更高兴。感谢。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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而不是String,比如

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

答案 2 :(得分:0)

在案例1中,创建了3个对象,“hello”,“world”和“helloworld”

在案例2中,在字符串池“hello”和“world”中创建了两个对象。即使字符串池中存在“World”对象,也会创建new对象。

相关问题