Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt - Reg: GC

 
Thiru Mu
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any one explain the code below, The answer is 2
class C
{
public static void main(String a[])
{
C c1=new C();
C c2=m1(c1);
C c3=new C();
c2=c3; //6
anothermethod();
}
static C m1(C ob1){
ob1 =new C();
return ob1;
}
} After line 6, how many objects are eligible for garbage collection?
[ September 06, 2007: Message edited by: Thiru Mu ]
 
Praveen Seluka
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I think only one object is eligible for garbage collection
 
Thiru Mu
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Praveen,
In my evaluation, I see the same .

here is the explanation,

class C
{
public static void main(String a[])
{
C c1=new C(); // OBJONE: here object OBJONE is getting created
C c2=m1(c1); // here c2 refers OBJTWO
C c3=new C(); //OBJTHREE: ct is created
c2=c3; //6 // c2 now refers OBJTHREE
anothermethod();
}
static C m1(C ob1){ // ob1 refers to OBJONE
ob1 =new C(); //now ob1 is refering a new object say OBJTWO
return ob1; // OBJTWO is returned

}
}

so at the line 6, c1 refers OBJONE , nothing refers OBJTWO because ob1 is a method local variable, and its life time is only when the method is getting executed..so OBJTWO is eligible for GC,
OBJTHREE is referenced by C2 C3.

am i right praveen? Please give your explanation.
[ September 06, 2007: Message edited by: Thiru Mu ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic