0

When we create a String using = we create (if it does not exist) a new String literal in the String pool. I know the String pool contains only unique values.

Step 1:

String var1 = "Java";

OK. We now have 1 literal in the String pool and 1 object created in the Heap. Now if we create String using new String() with the same literal value:

Step 2:

String var2 = new String("Java");

We now have 2 different objects created in the heap. The main question is: Do both String literals refer to the one in the String pool or do we have one String literal var1 - "Java" and one that's outside that String pool var2 - "Java"?

I just want to know do we have one literal or two literals or 1 in the String pool and one outside (waiting to be added to the String pool).

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Sv_BS
  • 1
  • 1
  • 3
    Only string literals are automatically interned in the string pool. String instances created any other way are not part of the pool unless you call `intern()` on them (which returns the cached instance, adding the current instance to the pool if not already present). And `new String("Literal")` involves two objects, one via a string literal, and another via the string constructor (i.e., not a string literal). – Slaw Jan 08 '23 at 10:47

0 Answers0