If the JVM has a string pool for memory optimization, then why does it create a new object each time we create a string using the new
keyword even though it exists in the string pool?
|
||||
Because you explicitly told it to! The
For the record, it is nearly always a mistake to call For older versions of Java, the This behavior of |
|||||||||||||||||||||
|
To give primitive style of declaration and for performance designers introduced String literals. But when you use When the objects created on heap, there is no way to share that memory with each other and they become completely strangers unlike in constant pool. To break this barrier between heap and constant pool
Remember that constant pool also a small part of heap with some additional benefits where sharing of memory is available. |
||||
|
To take advantage of string pooling you need to use |
|||||||||||||||||||||
|
When you write
then it creates a string object in heap just like other object which you create. The string literal "mystring" is stored in the string constant pool. From the Javadocs:
|
||||
|
Following object will be stored in String pool :
And following object will be stored in Heap (not in string pool):
|
|||||||||||||||||
|
To enforce garbage collection!. If you need some String just one time, then there is no point in keeping it in memory (for almost forever. Which is the case with Strings in constant pool). Strings which are not in the constants pool can be GCed like any other object. So, you should only keep frequently used Strings in the constants pool (by using literals or interning them). |
|||||||||
|
Strings created in the form of String literals ( |
|||||
|
new
means... – njzk2 8 hours ago