• 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

q on garbage collection

 
Ranch Hand
Posts: 303
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
At what point is the object obj eligible for garbage collection?
(Select one correct answer)
--------------------------------------------------------------------------------

public class Test058
{
public String m()
{
Object obj = new String("");
String str = null; //1
str = (String)obj; //2
obj = null; //3
return str;
}
}

--------------------------------------------------------------------------------

A: After line //1.
B: After line //2.
C: After line //3.
D: Never



The object is returned by the method and not eligible for garbage collection during the lifetime of the method.


I answered b, but the correct answer is d.

could someone please tell me y?
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jayashree,

Object obj = new String("");
creates a new String object with obj as reference and obj is of Object Type.

str, a String reference is set to null.

obj reference variable is assigned to str and has type casted to String since str is of type String.

Now, str reference and obj reference both point to the String Object.

obj is set to null. But still we have str reference pointing to the String Object,which was created when it had the reference obj.

Hence, the Answer is D : Never.

Regards,
vidhya
 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


at line 2. object reference "str" and object reference "obj" pointing same object.
at line 3. object reference "obj" = null.
but object reference "str" still refering to (have address of) that object.

hope it's helpfull to understand.
reply
    Bookmark Topic Watch Topic
  • New Topic