• 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
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

garbage collection question

 
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1 object only
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Did you just should on me? You should read this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic