I read many conflicting articles about memory allocation when creating String. Some articles say that a new statement creates a string on the heap, and a string literal is created on the String Pool [Heap], while some say that the new statement creates an object on the heap and another object on the string pool.
To analyze this, I wrote the following program that prints the hash code of a String char array and a String object:
import java.lang.reflect.Field; public class StringAnalysis { private int showInternalCharArrayHashCode(String s) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { final Field value = String.class.getDeclaredField("value"); value.setAccessible(true); return value.get(s).hashCode(); } public void printStringAnalysis(String s) throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException { System.out.println(showInternalCharArrayHashCode(s)); System.out.println(System.identityHashCode(s)); } public static void main(String args[]) throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException, InterruptedException { StringAnalysis sa = new StringAnalysis(); String s1 = new String("myTestString"); String s2 = new String("myTestString"); String s3 = s1.intern(); String s4 = "myTestString"; System.out.println("Analyse s1"); sa.printStringAnalysis(s1); System.out.println("Analyse s2"); sa.printStringAnalysis(s2); System.out.println("Analyse s3"); sa.printStringAnalysis(s3); System.out.println("Analyse s4"); sa.printStringAnalysis(s4); } }
This program prints the following result:
Analyse s1 1569228633 778966024 Analyse s2 1569228633 1021653256 Analyse s3 1569228633 1794515827 Analyse s4 1569228633 1794515827
From this conclusion, it is very clear that no matter how String is created, if the strings have the same value, then they use the same char array.
Now my question is: where is this chararray stored, is it stored on the heap or goes to permgen? I also want to understand how to distinguish between heap memory addresses and address memory addresses.
I have a big problem if it is stored in perdgen, as it will eat my precious limited space forward. and if the char array is not stored in permgen, but on the heap, then this means that String literals also use a lot of space [this is something that I never read].