String Pool and Immutability
Posted on 2004-04-26
I am learning Java String. I have two questions. the question is relevant to following code.
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
Now when I do s1==s2 the result is true. That's fine as I expected as they are pointing to the same literals.
But if I do s1==s3 the result is false. Why? I tought that for string class if you have String s1=""; and using String s = new String(""); are same its just which style you prefer. But now I think they are different.
Can someone please tell me what is going on here.
As I read, String pool is not garbage collected. So I thought maybe I can make my system to run out of memory. So I wrote a small program which keeps generating distinct string at run time. So as I think all these strings must be stored in the pool and never get garbage collect. But my system never went out of memory. I am running this program for more than two hours now. Why is that? Is the pool garbage collected?