From this Number of String Objects on stack overflow,I came to know that if we do some thing like :
String s = new String("ABC");
Then we have two objects
one on heap that is String
and one on constant
pool that is "ABC"
,
But today I took the heap dump and found there are two objects
on heap it self. I used MAT tool for the same please find the screen shot below.
So my query is if there are two Objects on heap one of Char[]
and other for String
class and one on constant pool then thus this means that
String s = new String("ABC")
will create 3 objects in total.
There seems to be repeated nonsense about string literals and the string pool all over the internet. Just to to emphasize, how heap in defined:
The Java® Virtual Machine Specification
2.5.3. Heap
The Java Virtual Machine has a heap that is shared among all Java Virtual Machine threads. The heap is the run-time data area from which memory for all class instances and arrays is allocated.
So, regardless of how a virtual machine implements it, all objects are living in the heap, as that’s how the term heap is defined. The heap is the memory, all object instances are allocated from, hence, all objects are allocated from the heap. In the past, objects for string literals and objects created via new
used to live in different memory regions, but still, all of those were part of the heap.
In recent JVMs, all String
instances are created in the same memory region, whether created for a literal or for an instance created via new
.
In either case, the string pool to manage string literals and “interned” strings is a table of references to these strings. The table itself may live outside the heap, the objects do not.
In your example, you have two String
instances and one char[]
array, because String
s are implemented as wrappers around char[]
arrays and both strings share the array. But that’s an implementation detail. In other (older) JVMs, that array got copied when you construct one string from another using the String(String)
constructor. So in these JVMs, your example would create two String
instances and two char[]
array instances.
Even more fancy, with up to date JVMs and an appropriate configuration, the JVM will identify String
instances with different arrays but identical content and change them to share an array to reduce the memory consumption. This feature is called String Deduplication. On Stack Overflow, see: String Deduplication feature of Java 8.