Search code examples
javagarbage-collection

Question about Garbage Collection for my OCA Exam


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;
// When this line is reached, what is eligible for the GC.
    }
}

Can somebody please explain what happens here? I understand that c1 and the Short are eligible for the Garbage Collector. But what happens with c2 and why isn't c3 also available for it? I might oversee something here but I would be glad for every input that helps me get around this topic. My OCA exam is next week and I still have trouble with this kind of stuff.

Edit: The comment of what is eligible for the GC.


Solution

  • Considering Java is pass-by-value, we know that Java isn't passing the object, it's passing a reference to the object.

    Because of this, when you did CardBoard c3 = c1.go(c2);, the method go(Cardboard cb) just copied the reference value of c2 to cb and therefore c2 is unharmed by the cb = null;. So, c2 is not eligible for GC.

    c3 never gets to be constructed as an object, it is just a variable of type CardBoard initialized to null. Thus, it cannot be garbage collected because it is not even created on the heap.