Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

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: 16084
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: 8981
19
  • 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.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!