From this output one thing is very clear that irrespective of how String is created, if Strings have same value then they share same char array
Not quite: this is happening because you start with one literal string, and create multiple instances from it. In the OpenJDK (Sun/Oracle) implementation, the backing array will be copied if it represents the entire string. You can see this in src.jar
, or here: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java#String.%3Cinit%3E%28java.lang.String%29
If you carefully construct your source strings such that they start from different character arrays, you'll find that they don't share the backing array.
Now my question is where is this chararray stored
To the best of my knowledge, the character array for a string literal is stored on the heap (those with better knowledge of classloading internals, feel free to comment). Strings loaded from files will always store their backing arrays on the heap.
What I do know for sure is that the data structure used by intern()
only references the String
object, not its character array.