Create new lines in regular memory and in the row pool

If, for example:

String str1 = "abc";
String str2 = new String("def");

      

Then

Case 1 : String str3 = str1.concat(str2)

will go into heap or pool?

Case 2 : String str4 = str2.concat("HI")

will go into heap or pool?

+1


source to share


2 answers


The first syntax (String str1 = "abc";)

creates only one String object and specifies one reference variable. The object is created in a pool of String constants maintained by the 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 normal memory. In addition, the string constant "newstring" will be put into the String constant pool.



So when we don't have a new keyword, we only have one String object in the pool of String constants.

0


source


In java, whichever string is created using the new keyword will be created in heap memory. If you create any String without using a new one, it will be created in the String pool and named String Constant. There will only be one copy of the String pool value, which means there won't be duplicates in the string pool.



0


source







All Articles