sayem siam sayem siam - 9 months ago 28
Java Question

how many objects are eligible for garbage collection when end line of main is reached?

My main problem is how many object is really created at executing the line

Dozens [] da = new Dozens[3];


And how many object will be eligible for garbage collection at the end of main function

class Dozens {
int[] dz = {1,2,3,4,5,6,7,8,9,10,11,12};
}

public class Eggs {
public static void main(String[] args) {
Dozens [] da = new Dozens[3];
da[0] = new Dozens();
Dozens d = new Dozens();
da[1] = d;
d = null;
da[1] = null;
// do stuff
}
}

Answer Source

After executing Dozens [] da = new Dozens[3]; a single object will be created. After the main method is finished, if you don't create another thread that uses the objects created in main, all the objects that you created will be available for garbage collecting.

public class Eggs {
  public static void main(String[] args) {
    Dozens [] da = new Dozens[3]; //one array object created
    da[0] = new Dozens(); // one Dozens object created
    Dozens d = new Dozens(); //one Dozens object created
    da[1] = d; 
    d = null; //nothing available for gc here, as there is still a referrence to that Dozens object (da[1])
    da[1] = null; //da[1] available for gc
    // do stuff
  }
}