Create New Strings in normal memory and in string pool [duplicate]

血红的双手。 提交于 2019-12-11 12:11:44

问题


If for example:

String str1 = “abc”;
String str2 = new String(“def”);

Then,

Case 1: String str3 = str1.concat(str2) will go in the heap or pool?

Case 2: String str4 = str2.concat(“HI”) will go in the heap or pool?


回答1:


In java, whichever String u create using new keyword will be created in heap memory. If you create any String without using new, it will created in String pool and it will be called as String Constant. There will be only one copy of String constant pool value which means duplicates wont be there in String pool.




回答2:


In the first syntax(String str1 = "abc";), just one String object is created and one reference variable pointing to it. The object is created in the String constant pool maintained by JVM. In the second case String str2 = new String("def");, two String objects are created. Since new is called, one String object is created in the normal memory. Also, the string constant "newstring" will be placed in the String constant pool.

So when we don't have New Keyword, we just have one String object is created in the String constant pool.



来源:https://stackoverflow.com/questions/25956404/create-new-strings-in-normal-memory-and-in-string-pool

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