Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

q on garbage collection

 
JayaSiji Gopal
Ranch Hand
Posts: 303
  • 0
  • Mark post as helpful
  • send pies
  • 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?
 
vidhya jay
Greenhorn
Posts: 15
  • 0
  • Mark post as helpful
  • send pies
  • 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
 
sanjeevmehra mehra
Ranch Hand
Posts: 75
  • 0
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic