• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

q on garbage collection

 
JayaSiji Gopal
Ranch Hand
Posts: 303
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the following code how many objects are eligible for garbage collection?
String string1 = "Test";
String string2 = "Today";
string1 = null;
string1 = string2;

A) 1
B) 2
C) 3
D) 0

I answered 0 but the correct answer is one.
I answered 0, bcos string1 is set to null, but in the very next line, is says string1 = string2.

plz explain.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jayashree, please quote the exact source of these questions. This one is clearly wrong.
 
John Neel
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i feel the answer 1 is correct.

as the object "Test" is not referred by any one, it can be garbage collected.

plz correct me if i were wrong
 
sandu sudhakar
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ref: article
http://www.javaranch.com/journal/200409/Journal200409.jsp#a1

"String Literals are not eligible for garbage collection".

So in this example, none of the objects are eligible for garbage collection.
Answer: 0
 
Mike Gershman
Ranch Hand
Posts: 1272
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From Bert Bates (who should know):
focus on non-String objects when you're studying GC, don't worry about GC and Strings together.

This is a problem with some mock exams, they have clever questions that are outside the exact scope of the exam.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic