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

garbage collection question

 
Naresh Gunda
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Gyan Shankar
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1 object only
 
Cristina Vinuela
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I think 1 Object as well.

In C c1=new C(); we have vble c1 ----> object C 1

When we call m1, we have a copy of c1 in ob1, because parameters are passed-by-value in java. So, c1,ob1-----> object C 1

In ob1 =new C(); we assign a new object to ob1.
c1------>object C 1
ob1----->object C 2

In C c2=m1(c1); we assign c2 to the object pointed by ob1 in m1, and ob1 doesn't exist anymore because we are out of m1.
c1------>object C 1
c2----->object C 2

C c3=new C(); is easy
c1------>object C 1
c2----->object C 2
c3----->object C 3
In c2=c3 we assign the object pointed by c3 to c2
c1------>object C 1
object C 2
c2,c3----->object C 3

So, in line 6, there is only one object which is not being referenced (object C 2) and it's eligible for garbage collection.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic