Why String created using new operator creates string literal in string pool
The Java language was designed this way. Anything you use between double quotes is a compile-time constant and goes into the string pool. So in your case:
String a = new String("abc");
"abc"
will be resolved as a compile-time constant and thus added to the String constant pool for the current JVM.
The value a
will then be resolved at runtime and added to the heap at runtime.
source to share
First of all, let me clear you as you write
String str=new String("abc");
a new object is created regardless of the content in the variable. Second, when you create a String with
String str="abc";
at this time, this content will be searched in the pool. If any line matches the same content as the new then only the link will be created on the stack, but will point to the older heap location. Got?
source to share
I believe in creating string objects using new operator, don't create object in constant string pool for below reason 2.
-
The Intern () method is used to add a string object to the string constant pool. If the string object is present in the string constant pool, then there is no intern () method.
-
String literal = "abc"; String object = new String ("abc"); System.out.println ("result =" + literal == object); // false
If the string object is present in the string constant pool at compile time, then the result should be true.
Please correct me if I am wrong.
source to share