Results 1 to 6 of 6
  1. #1
    DrMath is offline Member
    Join Date
    Sep 2009
    Posts
    10
    Rep Power
    0

    Question Garbage Collection Question

    Given:
    class CardBoard {
    Short story = 200;
    CardBoard go(CardBoard cb) {
    cb = null;
    return cb;
    }
    public static void main(String[] args) {
    CardBoard c1 = new CardBoard();
    CardBoard c2 = new CardBoard();
    CardBoard c3 = c1.go(c2);
    c1 = null;
    // do Stuff
    } }
    When // doStuff is reached, how many objects are eligible for GC?
    A. 0
    B. 1
    C. 2
    D. Compilation fails
    E. It is not possible to know
    F. An exception is thrown at runtime

    ANSWER: (C)

    However, how to see that its 2 here?
    Obviously, most ppl mistake it to be a 1 at line: c1 = null;

  2. #2
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    A CardBoard has a story which is another object.

  3. #3
    DrMath is offline Member
    Join Date
    Sep 2009
    Posts
    10
    Rep Power
    0

    Default

    I see...
    So when an instance is created - all its variables are considered too...

  4. #4
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    Variables that are objects (object references) are considered.

  5. #5
    Mr.Beans's Avatar
    Mr.Beans is offline Senior Member
    Join Date
    Apr 2009
    Location
    Virginia Beach, Virginia
    Posts
    149
    Rep Power
    0

    Default

    I believe that it's two because c1 and c3 are both null.
    Since we can't see the story class we can't be sure what is pointed to it.

    Then again, I'm a beginner too.


    Mr. Beans

  6. #6
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    No. No instantiated object was ever created to assign to c3, and even if c2 had been assigned to c3 (as that method call implies, although it only returns null), there would still only have been one (actually 2 because of the "embedded" Short), but with two references refering to it, and it is not references that need to be garbagecollected.

Similar Threads

  1. Java Garbage Collection and destructors
    By riddhik84 in forum New To Java
    Replies: 1
    Last Post: 09-30-2009, 09:48 AM
  2. Replies: 3
    Last Post: 01-23-2009, 08:53 AM
  3. How setting an Object to null help Garbage Collection?
    By piyu.sha in forum Advanced Java
    Replies: 3
    Last Post: 10-06-2008, 07:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •