Java String object creation

2019-05-21 13:48发布

I have been reading Java String object and I had this question -

String x="a";
String y="b";

Does it create two objects in Java?

4条回答
走好不送
2楼-- · 2019-05-21 13:52

When ever a String is initialized using new operator its new object is created. Like if you do

String s1= new String ("string");

String s2=new String ("string");

String s3=new String ("string");

All of the three will create a separate String object in the heap. Whereas if all the above strings are initialized without new operator then, firstly the string will be checked in string pool for its existence. If required string exist then the new reference will start pointing to the existing string.Otherwise it will create new sting in the pool. For example:

String s1= "string";

String s2="string";

String s3="string1";

In the above example only two string will be created in string pool ("string" and "string1"). Where String s1 and s2 will refer to single object "string" and s3 will refer to another string object "string1".

查看更多
在下西门庆
3楼-- · 2019-05-21 14:04

String with literals gets created in String Pool. whereas String through new operators gets created in Heap Memory.

Advantage of creating String through literals is if that String value is already available in String Pool then you get the same reference where through new operator everytime you create a new object new reference.

In your case you will get same reference. so only object.

查看更多
贼婆χ
4楼-- · 2019-05-21 14:05

String object will be created by each line, unless they already exist in string pool...if they exist in string pool only a reference will be linked to your variable and no new objects will be created.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-05-21 14:18

Those two lines of code will not create any objects. String literals such as "a" are put in the string pool and made available upon class loading.

If you do

String x = new String("a");
String y = new String("b");

two objects will be created in runtime.

These questions/answers should cover follow-up questions:

查看更多
登录 后发表回答