| Author |
String and Garbage Collection
|
Yun Hao
Greenhorn
Joined: Nov 19, 2004
Posts: 11
|
|
Suppose in the code, we have statement like this: 1. String s1="My String"; 2. s1="Another String"; my question is after line 1, whether there is object created? After line 2, whether there is object eligible for garbage collection?
|
 |
Premil Jacob
Ranch Hand
Joined: Sep 10, 2004
Posts: 30
|
|
both the strings you created i.e, 1. String s1="My String"; 2. s1="Another String"; both the strings "My String" and "Another String" are intern'd. What that means is that both the strings will only garbage collected when the java runtime exits.
|
Thanks,<br />Premil<br /> <br />SCJP 1.4
|
 |
Yun Hao
Greenhorn
Joined: Nov 19, 2004
Posts: 11
|
|
Thanks Permil. I want to be much clearer. You are saying that no object is eligible for garbage collection after line 2. Is that what you mean? This is what I thought first. Because "My String" is in the string literal pool.If I change the line 1 to s1=new String("My String"); after line 2, I think one object is eligible for garbage collection. Thanks
|
 |
Francis Palattao
Ranch Hand
Joined: Sep 22, 2004
Posts: 91
|
|
If I change the line 1 to s1=new String("My String"); after line 2, I think one object is eligible for garbage collection.
Yes I agree the "My String" literal is an object created but no reference to it. So it is eligible for garbage collection but I think since it is a literal I heard it will never be garbage collected because there is a reference to it from the string literal pool.
|
SCJP 1.4 <br />SCWCD 1.4 (preparing)<br />SCBCD 1.3 (coming soon)
|
 |
 |
|
|
subject: String and Garbage Collection
|
|
|