Gireesh Chetty wrote:Hi Jain,
Can you explain me the following two programs out put
Let us see what happens when a .java file is compiled by the compiler: -
a). The compiler will search for all the distinct string literals in your java code, and check whether that literal is already present in Heap
b). If the literal is not present in heap, it creates one, and add a reference to that literal in the String literal constant pool..
c). Now any reference to that literal further in your program will be replaced by the reference you added in the constant pool..
So, in this case, you are actually placing one object on heap and both your local variables are assigned a reference to that object..
Now consider your second code...
When you write: -
str = "Hello" and
str = new String("Hello");
You are actually creating two different object on heap both containing the same content..
Similar is the case with your this code: -
Here, str1 and str2 points to two different objects on the heap with the same content "ab"
Thus the result..