1

When we declare a String literal like

String str = "abc";

only one object is created in String pool. But when we create it like

String str = new String("abc"); 

2 objects are created one in heap memory other in the String pool. whats the purpose of creating an entry in string pool when you already have an object placed in the heap memory?

fabian
  • 80,457
  • 12
  • 86
  • 114
ShreyJo10
  • 27
  • 5
  • Creating a `String` object explicitly from a string literal, as you are doing in the second example, is never useful. You never need to write this kind of code in a real Java application. – Jesper Dec 14 '16 at 10:19
  • Uhm, what do you think is created first? The constructor parameter or object created via invokation of the constructor? – fabian Dec 14 '16 at 10:19

1 Answers1

1

whats the purpose of creating an entry in string pool when you already have an object placed in the heap memory

If heap object gets garbage collected and "abc" is required again, then JVM can just point to pool. And, that's one more reason to prefer literal over new for String.

See this: Why to create a String object using new

What is the purpose of the expression "new String(...)" in Java?

Community
  • 1
  • 1
Azodious
  • 13,752
  • 1
  • 36
  • 71