• Post Reply Bookmark Topic Watch Topic
  • New Topic

GC  RSS feed

 
dolly shah
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
12. From the following code how many objects are eligible for garbage collection?

String string1 = "Test";
String string2 = "Today";
string1 = null;
string1 = string2;

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

Why only 1 is eligible got GC. I think string1=null & string1=string2, So that string2 also becomes null & eligible for GC. Can anyone explain?
 
Siphiwe Madi
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
The object that becomes eligible for Garbarge collection is "Test", meaning only 1 in total object(s) are eligible for GC.

The other object "Today" is not eligible for GC because the String identifier string1 at line 4 is now pointing to it.

the flow is

1. string1 is pointing to "Test"
2. string2 is pointing to "Today"
3. string1 (set to null) therefore the connection to object "Test" is lost, then that object has no reference which makes it eligible for GC at that point.
4. string1 is given the address of string2 which points to "Today",

at that point you've got 2 identifiers (i.e. string1 and string2) pointing to the same object (i.e. "Today"), therefore there is still a reference to 1 object.

Hope this helps

Regards,
Siphiwe M

SCJP 1.5 (Aspirant)
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dolly, please quote your sources when you post questions from mock exams - it's polite to the author of the mock exam, and you help your fellow Ranchers so that they can find the mock exam.
 
Bert Bates
author
Sheriff
Posts: 8954
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
because of the String constant pool, the real exam will NEVER have GC questions that use String objects.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!