This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Dan's GC 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 "Dan Watch "Dan New topic

Dan's GC question

GM Shobha

Joined: Apr 22, 2003
Posts: 10
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??
G Nadeem
Ranch Hand

Joined: Apr 25, 2003
Posts: 48
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

Joined: Apr 22, 2003
Posts: 10
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.
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1090
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.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: Dan's GC question
It's not a secret anymore!