1

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?

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
  • all strings go in the pool. `New String` will create a new string even a same string is existed in the pool – pms Sep 21 '14 at 06:23
  • String s = "abc"; // creates one String object and one // reference variable In this simple case, "abc" will go in the pool and s will refer to it. String s = new String("abc"); // creates two objects, // and one reference variable In this case, because we used the new keyword, Java will create a new String object in normal (nonpool) memory, and s will refer to it. In addition, the literal "abc" will be placed in the pool. – aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Sep 21 '14 at 07:45
  • looks like dupe http://stackoverflow.com/questions/2486191/java-string-pool and http://stackoverflow.com/questions/3801343/what-is-string-pool-in-java – dave_thompson_085 Sep 21 '14 at 17:05

2 Answers2

0

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.

kumar
  • 708
  • 4
  • 15
  • 39
0

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.

Peter O.
  • 32,158
  • 14
  • 82
  • 96