Skip to content
Advertisement

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement