My Question is what's the use of creating string object in string pool as well as on Heap when we declare String as String a = new String("abc");
What is the advantage ?
And why not we create string in heap when we create string as String a = "abc"
.
When we create a string literal, the JVM first check that literal in the String pool. If the literal is already present in the pool, it returns a reference to the pooled instance. If the literal is not present in the pool, a new String object takes place in the String pool.
If we create a String using new(), then a new object is created in the heap memory even if that value is already present in the heap memory.
When we create a String object using the new() operator, it always creates a new object in heap memory. On the other hand, if we create an object using String literal syntax e.g. “Baeldung”, it may return an existing object from the String pool, if it already exists.
The main difference between String Literal and String Object is that String Literal is a String created using double quotes while String Object is a String created using the new() operator. String is a set of characters. Generally, it is necessary to perform String operations in most applications.
The java language was designed like that. 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 will be added to the String constants pool for the current JVM.
Next, the value of a
will be resolved at run-time and will be added to the heap during run-time.
First, I recommend that you not use new String("abc")
because it behaves as you described. Second, when you use new
you should expect a new Object
instance will be created and it is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With