| Author |
Strings and GC
|
luis meira
Ranch Hand
Joined: Apr 18, 2002
Posts: 55
|
|
When is the string object created in line2 first subjected to Garbage Collection(Assuming amethod is part of valid java class) 1public void aMethod(){ 2 String s1 = "Hello"; 3 String s2 = "pal"; 4 s1 = s1 + s2; 5 System.out.println(s1); 6} A.After the execution of method, i.e., after line 6. B.After line 4. C.After line 3. D.After line 2. i would shouse A. but acording to the exam it's B i don't understand why ?
|
 |
Sayed Ibrahim Hashimi
Ranch Hand
Joined: May 17, 2001
Posts: 148
|
|
Originally posted by luis meira: When is the string object created in line2 first subjected to Garbage Collection(Assuming amethod is part of valid java class) 1public void aMethod(){ 2 String s1 = "Hello"; 3 String s2 = "pal"; 4 s1 = s1 + s2; 5 System.out.println(s1); 6} A.After the execution of method, i.e., after line 6. B.After line 4. C.After line 3. D.After line 2. i would shouse A. but acording to the exam it's B i don't understand why ?
The String object that is created in line 2 is the String that contains "Hello", the reference to it is s1. In line 4 you are creating a new String object that contains "Hellopal". Then you make s1 point to that new object. So there is no reference pointing to "Hello", so it is now subject to gc. When dealing with Strings you have to keep in mind that String objects are immutable so when you do s1+s2, you aren't appending s2 to s1 but you are creating a new String. Hope this helps.
|
SCJP 1.4<br /><a href="http://www.cise.ufl.edu/~sih" target="_blank" rel="nofollow">www.cise.ufl.edu/~sih</a>
|
 |
luis meira
Ranch Hand
Joined: Apr 18, 2002
Posts: 55
|
|
Originally posted by Ibrahim Hashimi: The String object that is created in line 2 is the String that contains "Hello", the reference to it is s1. In line 4 you are creating a new String object that contains "Hellopal". Then you make s1 point to that new object. So there is no reference pointing to "Hello", so it is now subject to gc. When dealing with Strings you have to keep in mind that String objects are immutable so when you do s1+s2, you aren't appending s2 to s1 but you are creating a new String. Hope this helps.
am i wrong or string literal's were not subject to GC ? if not what are the exceptions. LFM
|
 |
Corey McGlone
Ranch Hand
Joined: Dec 20, 2001
Posts: 3271
|
|
Unfortunately, I think the exam is incorrect - String literals are not available for garbage collection. Had the code looked like this: Then, I believe the answer the exams provides would be correct. String literals, however, are never garbage collected. If you have any questions about this, please refer to this thread. It covers the topic in great detail. Where did you find that question? I hope that helps, Corey
|
SCJP Tipline, etc.
|
 |
 |
|
|
subject: Strings and GC
|
|
|