• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strings and GC

 
luis meira
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
luis meira
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic