Why String created using new operator creates string literal in string pool

My question is what is the use of creating a string object in the string pool as well as on the heap when we declare String as String a = new String("abc");

What is the advantage?

And why don't we create a string on the heap when we create a string as String a = "abc"

.

+3


source to share


4 answers


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.

+4


source


First, I recommend not using new String("abc")

it because it behaves like you described. Secondly, when you use new

, you should expect a new instance to be created Object

and it will.



+3


source


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?

0


source


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.

0


source







All Articles