Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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".

like image 200
RishiKesh Pathak Avatar asked Nov 21 '14 06:11

RishiKesh Pathak


People also ask

Does new string create in string pool?

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.

What happens when we create string using new operator?

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.

How is the creation of string using new different from that of a literal?

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.

What is the difference between string literal and new string ()?

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.


2 Answers

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.

like image 101
TheLostMind Avatar answered Oct 16 '22 23:10

TheLostMind


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.

like image 20
Elliott Frisch Avatar answered Oct 16 '22 23:10

Elliott Frisch