Anj Jo Anj Jo - 1 year ago 37
Java Question

Garbage Collection of Objects passed as arguments and being set to null in a method

I have was trying to understand this question but could not get settled with the answer provided in the book. Can somebody explain to me? Question is given bellow.

class CardBoard {
Short story = 5;

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 // do stuff is reached, how many objects are eligible for garbage collection?

Given answer is 2 objects. Only one CardBoard object (c1) is eligible, but it has an associated Short wrapper object that is also eligible

I dont understand why object c1 alone is eligible for garbage collection.

Two object are created, c1 and c2.

For object c3 we are passing c2 to c1.go() method. And that that is set to null and returned object is asigned to c3.

In the method c1.go(), object that cb reffering to (which by my undertanding, the same object that c2 reffering to ) is set as null. Won't that make the object that c2 reffering to will also be available for garbage collection?

Answer Source

Java is pass-by-value. When you do CardBoard c3 = c1.go(c2);, the instance pointed to by c2 is passed to go() but the moment you do cb=null, the original c2's cb is NOT set to null, a new null reference aconst_null is pushed onto the stack and returned. Hence, there are only 2 objects (Short and c1) that are eligible for GC.

PS : As Andreas says, Short values are cached for values between -128 and 127 and hence in your case, the same Short instance will be reused. So only one object will be eligible for GC. If your Short value is out of that range, then 2 Objects will be eligible for GC.