File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes garbage collection question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "garbage collection question" Watch "garbage collection question" New topic

garbage collection question

Naresh Gunda
Ranch Hand

Joined: Oct 15, 2005
Posts: 163
class C
public static void main(String a[])
C c1=new C();
C c2=m1(c1);
C c3=new C();
c2=c3; //6
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

Joined: Dec 12, 2005
Posts: 65
1 object only

SCJP(1.4), SCWCD(1.4), SCBCD(1.3), SCDJWS
Cristina Vinuela

Joined: Dec 12, 2005
Posts: 6

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.
I agree. Here's the link:
subject: garbage collection question
jQuery in Action, 3rd edition