Does String created using new operator resides on Heap and also on String pool?
Or may be can some one point me to some document or a link which will guide me String pool behavior?
Does String created using new operator resides on Heap and also on String pool?
Or may be can some one point me to some document or a link which will guide me String pool behavior?
String literals in your java code resides in a String pool but created using new does not.
String Pool is kind of a cache and is also stored in the heap.
Case 1-
String s1="world";
String s2="india";
String s3="world";
here two objects will be created in Pool. s1 and s3 will point to same object. string literals go to pool memory.
Case 2-
String s1=new String("world");
String s2=new String("india");
String s3=new String("world");
here three objects will be created on heap.
new word use heap memory to create objects.
hope I was able to tell.
see link for more detail understanding.
String created using new operator resides on Heap not in String pool(String pool is also present in the heap memory).
But you can move that object into the pool by using String.intern()
.
After invoking String.intern()
on the String, if the String created by using new
keyword is already present in the pool then reference of pooled object will be returned. So now it will point to the pooled object instead of previous one.
More details
Actually nothing is promised.
The compiler/JVM may decide to create it in the String pool, but also on the neap. Today it may create you Strings in the pool of String literals, tomorrow after the JVM update it may create them on the heap, for exactly the same code.
The key thing is that your code should not depend on the fact where your Strings are create.
For example - avoid == operator for comparison of String values.