Apperently, the answer here is 2, according to the book I'm reading, but I still don't understand why. It says that after line "// do stuff", 2 objects will be eligible for GC.
Can someone please explain it to me step by step? And is there like a trick to knowing how many objects are eligible for garbage collection after a certain line in the code? Because we were told that those kinds of questions (how many are elligible for gc) will appear on the test.
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
}
}
And yeah, the answer is "2 objects will be eligble for Garbage Collection after the line "// do stuff"", but I still don't understand why.
In this image, it also says why the answer is 2, but the explanation just made it A LOT more confusing for me.
Image from the SCJP book we're told to read.
It doesn't even explain what happened to the other objects.
EDIT:
So according to you guys, it's C1 and C3 that are eligible for GC, and I can see why because C1 has been set to null and C1.GO(C2) returns null to C3.
But according to the book, it's only C1 that is eligible, and the answer is 2 because of the Short wrapper. I have no idea why that is, and what even is the Short wrapper object.