1 Reply Latest reply: Jun 27, 2013 7:49 PM by rp0428 RSS

    objects & garbage collection

    7998ff07-e5e1-415c-be64-14023ec806f5

      Hi. There is a question in scjp preparation and I wish to know more about the explained answer:

       

      Given:

      3. class Dozens {

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

      5. }

      6. public class Eggs {

      7. public static void main(String[] args) {

      8. Dozens [] da = new Dozens[3];

      9. da[0] = new Dozens();

      10. Dozens d = new Dozens();

      11. da[1] = d;

      12. d = null;

      13. da[1] = null;

      14. // do stuff

      15. }

      16. }

      Which two are true about the objects created within main(), and eligible for garbage collection

      when line 14 is reached?

      A. Three objects were created

      B. Four objects were created

      C. Five objects were created

      D. Zero objects are eligible for GC

      E. One object is eligible for GC

      F. Two objects are eligible for GC

      G. Three objects are eligible for GC

      Answer:

      ® ✓ C and F are correct. da refers to an object of type "Dozens array," and each Dozens object

      that is created comes with its own "int array" object. When line 14 is reached, only the

      second Dozens object (and its "int array" object) are not reachable.

       

      Can anyone tell me why its mentioned that there are 5 objects are reported created here.

      Also doesn't defining the array of objects create the objects? E.g., in the line number 8, I see three element array is created, doenst this mean 3 objects are instantiated?

       

       

      Thanks

        • 1. Re: objects & garbage collection
          rp0428

          >

          Also doesn't defining the array of objects create the objects? E.g., in the line number 8, I see three element array is created, doenst this mean 3 objects are instantiated?

          >

          What is your reasoning for thinking that creating a PLACE to hold three instances has ANYTHING to do with creating those instances?

           

          If you move three bar stools to the kitchen counter in your home does that automatically create a person sitting at each bar stool?

           

          If you create an egg carton that can hold a dozen eggs does that automatically create 12 eggs? If it did why do we need chickens?