posted 14 years ago
There is a strong difference between the two.
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.
Any corrections, please point it out to me!!!
Regards,
Sriram