• 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
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Dan's GC question

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Q {
private int id;
public void finalize() {System.out.print(id);}
public Q(int i) {id = i;}
}
class R {
public static void main(String[] args) {
Q q1 = null;
for (int i = 0; i < 10; i++) {
q1 = new Q(i); // 1
}
System.gc(); // 2
}
}

When the processing of line 2 begins how many objects of type Q that were created at line 1 are eligible for garbage collection?
Answer 10 or 9??
 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Shobha,
line 2 is a part of main method, and q1 is object holding variable declared within main method,(Q q1=null). now total objects created within 'for' loop are 10. right. however only the last object created (when i==9) will be referenced by (and stored in,roughly speaking) q1. object created from i==0 to 1==8 (i.e 9) will be eligible for GC, as we have not been 'saving' them any where.
 
GM Shobha
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Nadeem,
Sometime back, question below was discussed in this forum.
public static void main(String args [])
{
for(int i=10;i>0;i--){
{
String s =new String(�Hello�);
}
System.out.println(�world�); // 9
}
How many objects eligible for GC at line no 9 ? & the answer given was 10.
Pl verify how is this problem different from the above.
 
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Shobha
Well there's a bit of difference between the two codes you have supplied. In the former case(the first post) the variable q1 of type Q is declared outside the for loop so is available after the for loop, but in the later case the variable s of String type is declared in the for loop and hence is not available once the for loop is over. So it is eligible once the for loop is over.
 
Popeye has his spinach. I have this tiny ad:
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic