Win a copy of Murach's MySQL this week in the JDBC and Relational Databases 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

GC

 
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 9050
21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
because of the String constant pool, the real exam will NEVER have GC questions that use String objects.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic