Java 字符串对象创建

Java 字符串对象创建,java,string,object,immutability,stringbuffer,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); 我想知道在每种情况下创建了多少个对象。因为字符串是不可变的,所以一旦给它赋值,对象就不能被重用(这是我目前理解的,如果我错了,

我是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解释这一点,我会更高兴。谢谢。

正如您正确地提到字符串是不可变的,下面创建了
3个字符串文本对象

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 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个对象
,而在案例1中使用
StringBuffer
,会创建3个对象,“hello”、“world”和“helloworld”


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

在之前的文章中,您可以很容易地获得有关此主题的大量教程和文章,这些教程和文章非常清晰地解释了每一件事。不要问这样愚蠢的问题,因为你只需点击一下谷歌就可以很容易地得到答案。正确地做家庭作业,同时诚实地做一些事情,如果你有一些问题,欢迎你提出问题。我没有足够的声望来投票否决或关闭这个网站。不要期望用勺子喂食。这个链接可能会帮助你:我不知道你为什么会回答这样的问题。。。但是干得好。不要期望OP投票或选择这个答案。他将阅读
3
2
,并将其添加到家庭作业中,从此再也听不到任何消息!据我所知,不允许JVM在字符串池(SCP区域)内进行垃圾收集。只有在整个JVM关闭时,所有字符串才会被销毁。如果我错了,请告诉我。^^同意。当字符串被创建为文本时,它们的处理方式不同(在本例中不是GCed)。另外,在第三个示例中,我相信创建了3个字符串:1。)“hello”2。)“world”3。)“Some more”耶!。这是链接:@ShaileshSaxena对,不知道我是怎么错过的:p
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