This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
1. String strNameOne = "coderanch";
In this case you are creating a string reference in the literal pool.
And the main issue here is that the String created does not get garbage collected.
Reason: suppose you make strNameOne = null;
In this case you would have released the reference from the local variable table.
But still, there will be one reference existing from the literal pool table to this object "coderanch".
And so the object will not be ready for GC.
2. String strNameTwo = new String("coderanch");
In this case, you will have only one reference from the local variable table.
There will be no reference from the literal pool table.
So, if you make strNameTwo = null;
In this case, you would have released the reference from the local variable table.
So, the object "coderanch" will be ready for GC.
All the more....
In case1, if another object is created the same way... like....
String string3 = "coderanch";
string3 will also point to the same object "coderanch" as pointed by strNameOne variable.
Because, the JVM will look for the object created this way and if the object is already seen in the String Literal pool, then the variable will be pointed to the same object, else the object will be added to the heap and the reference will be put in the literal pool.
then the variable will be pointed to the same object, else the object will be added to the heap and the reference will be put in the literal pool.
I dont think reference will be put in literal pool.
Suppose we have
then JavaRanch literal will be in String Literal Pool. Object created will be in heap memory area and reference vairable str will be placed in heap/stack delending upon instance variale/local variable respectively.
Let me know in case this is not correct understanding.
Joined: Jan 09, 2008
The string literal pool and intern() method are very interesting but
how is the pool used in practical situations?