0

Consider the following example :

String s1 "Hello";

String s2 = "World";

String s3 = s2 +s3;

In the above example how many objects are created in Stringpool? Is string s3 added to Stringpool or it is separate object in Heap memory or does JVM creates new object in heap and add it to stringpool as well? Thanks in advance :)

jCoder
  • 41
  • 2
  • 8
  • Strings are *always* in the heap memory. The string pool is a table of *references* to some of the string instances. And, no, the string created by `s2 + s3` will not be referenced by the string pool, unless you change the declaration of `s2` and `s3` to `final`, as then, they are compile time constants, which makes `s2 + s3` a compile time constant too. – Holger Nov 23 '17 at 16:17
  • @Holger this sort of flushes my entire understanding of string pool, when u say that references are in the pool and not instaces. There is a whole theory spread online that instances are in the pool. Its actually also easier to understand the pool this way unfortunately. What would happen if abc string is the pool and we create another String literal with the same content? Are all referenced touched to see where they point to and this new reference put in the pool also? – Eugene Nov 23 '17 at 16:40
  • @Eugene: the pool works very similar to a `HashMap`. So when you call `someString.intern()`, the outcome is very similar to `pool.computeIfAbsent(someString, Function.identity());`, but of course, when the JVM looks up a string for a literal, it surely uses an optimized procedure, using the character contents stored in the class file for looking up, only creating a `String` instance in the heap if none has been found. [As already said](https://stackoverflow.com/questions/47399482/how-many-objects-are-created-when-we-write#comment81792751_47399482) strings are “in the pool” only conceptually… – Holger Nov 23 '17 at 16:53

1 Answers1

0

In this case 3 Strings will be created in String pool. One for Hello, one for WorLd and one for s3 which is now HelloWorld as Strings are immutable.

Even if you do something like s1=s1+"World1"; then also it will be a new String (HelloWorld1) in String pool as it will be a new String created for that modification and s1's old reference to Hello will be still there as un-referenced String.

TechSingh
  • 331
  • 4
  • 7