4

If I write something like this:

String s1 = new String("ABC");
String s2 = "ABC";

In which scenarios does the string pool get updated? The first, second or both?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Deepak Sharma
  • 109
  • 2
  • 12

4 Answers4

3

In the above programming code ,when string pool get updated?

The first statement will update/add to the String pool with "ABC" String literal, but create another object in the heap and the variable s1 will refer the heap object.

The second statement will refer the already created Pool String object.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
  • I guess if you run this code the second time (or some other piece of code has previously created a literal "ABC"), the first statement will refer to the already created pooled object. In fact, does not the classloader update the string pool with the class' literals when the class is loaded into the JVM (even before the code is run)? – Thilo Apr 03 '14 at 09:05
2
String s = new String("ABC");

this always create a new String object on the heap and add "ABC" to the pool(if not present).

String s= "ABC";

Whereas this line is called string literal. It checks whether the string pool already has the same string "ABC" or not. If present then s will refer to that object otherwise a new object will be created.

Conclusion: new String() will always create a new object and string literal checks the string pool before creating one.

  • +1. But I don't think the code will "check whether the string pool already has the same string". The classloader should do that when the code is loaded. When it is run, it already points to a pooled instance. – Thilo Apr 03 '14 at 09:32
1
 String s1=new String("ABC");//creates two objects and one reference variable  

In your case, JVM will create a new String object in normal(nonpool) Heap memory and the literal "ABC" will be placed in the string constant pool.The variable s1 will refer to the object in Heap(nonpool).

String Constant Pool

String objects created with the new operator do not refer to objects in the string pool but can be made to using String’s intern() method. The java.lang.String.intern() returns an interned String, that is, one that has an entry in the global String literal pool. If the String is not already in the global String literal pool, then it will be added.

enter image description here

Whenever you use new keyword to create String Object,it will create in Heap and then it will check the String Constant Pool for the same String Literal.If SCP doesn't contain that String literal then Only it will create String literal in the SCP.

Gundamaiah
  • 780
  • 2
  • 6
  • 30
0

Nope. Strings created with the constructor never enter the string pool. In the example, two separate objects are created. Therefore:

s1 != s2

Stefanos
  • 25
  • 4