(You can check this answer, but I will try to make it a bit shorter.)
First thing to realize is that String
is an object backed by char[]
array, so the String itself can be in different place in memory than the char array containing the actual letters.
From source:
public final class String implements ... {
/** The value is used for character storage. */
private final char value[]; // <- String is backed by this array
...
}
So to your questions:
Where are those string text i.e character arrays stored in memory ?
Both String
object and the backing array are stored on the heap, even for compile-time strings. String pool contains only references to the strings.
Does "I belong to String pool" character array is present inside String pool and "I'm present on Heap space" character array actually present on the Heap Space ?
No, everything is allocated on the heap. String pool contains only the references.
In short, can anyone please explain the storage locations of String literal reference, String literal text, String object reference s2, String object text etc.
Let's start with the String
objects. There will be 3 string objects, original "I belong to String pool"
, "I'm present on Heap space"
and the newly created "I'm present on Heap space"
.
However there will be only 2 backing arrays, since the 2nd and 3rd string from previous point will be backed by same char array. (You can look into String(String)
constructor).
In the String pool, there will be 2 references: to the original "I belong to String pool"
and "I'm present on Heap space"
On your stack, you will have also 2 String references, s1
will be the same as in the string pool (= it will point to the same address), but s2
will be different (because you demanded a new
String).