Java String object creation

孤街醉人 提交于 2019-12-06 11:34:46
aioobe

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:

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".

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!