Java String object creation

六月ゝ 毕业季﹏ 提交于 2019-12-22 17:29:15

问题


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?


回答1:


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:

  • Questions about Java's String pool
  • How many Java objects are generated by this - new String("abcd")



回答2:


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:


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:


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.



来源:https://stackoverflow.com/questions/26083383/java-string-object-creation

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