After reading these discussions - question 1, question 2, article
I have the below understanding of Java String Constant Pool (Please correct me, If I am wrong):
When the source code is compiled, compiler look for all the string literals (The ones put into double quotes) in our program and create distinct(No duplicates) objects in the heap area and maintain their references in a special memory area called String Constant Pool (An area inside method area). Any other string objects are created at run time.
Suppose our code has the following statements:
String a = "abc"; //Line 1
String b = "xyz"; //Line 2
String c = "abc"; //Line 3
String d = new String("abc"): //Line 4
When the above code is compiled,
Line 1: a String object "abc" is created in heap and this object is referenced by variable a and String Constant Pool.
Line 2: Compiler searches String Constant Pool for any existing reference to the object "xyz". But does not find one. So, it creates object "xyz" and puts its reference in String Constant Pool.
Line 3: This time compiler finds the object in String Constant Pool and does not make any additional entry in pool or heap. Variable c just refers to existing object which is also referred by a.
Line 4: The literal in Line 4 is present in String Constant Pool. So, no more entry is made in pool. At run time however another String object is created for "abc" and its reference is stored in variable d.
Now I have the following questions/doubts:
- Is that what happens exactly which is described above?
- How does the compiler creates object? As per my knowledge, objects are created at Run time and heap is a Run time memory area. So, how and where does String objects are created at the time of compilation!
- Source code can be compiled in one machine and run in a different machine. Or, even in the same machine they can be compiled and run in different time. Then how those objects (created in compile time) are recovered?
- What happens when we intern a String.