问题
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