Search code examples
javagarbage-collectionpass-by-valuescjp

Garbage collection - why is c3 not eligible for collection in this example (SCJP 6)


Taken from SCJP 6 prep book -

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

The correct answer is C - " Only one CardBoard object (c1) is eligible, but it has an associated Short wrapper object that is also eligible."

My question is why is c3 not eligible for collection?

My thoughts are -

c1.go(c2) sets the local reference variable, cb (which is a copy of c2), to null and then returns cb which is assigned to c3. I know that the reference variable for c2 itself cannot be modified in the method, only the object behind it. However it would appear to me that the copy of the reference variable, cb, is set to null and assigned to c3. Why is c3 not set to the returned null in this instance?


Solution

  • There is no object related to c3. Its value is null, so there's nothing to collect.