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?
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?
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.
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.
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 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.
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.
Nope. Strings created with the constructor never enter the string pool. In the example, two separate objects are created. Therefore:
s1 != s2