This week's book giveaways are in the Scala and Android forums.
We're giving away four copies each of Machine Learning Systems: Designs that scale and Xamarin in Action: Creating native cross-platform mobile apps and have the authors on-line!
See this thread and this one for details.
Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

GC  RSS feed

 
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?
 
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)
 
Java Cowboy
Sheriff
Posts: 16083
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.
 
author
Sheriff
Posts: 8977
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.
 
grapes are vegan food pellets. Eat this tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!