0

Please tell me how many objects are eligible for garbage collection?

public class X {

    static X fun(X ref) {
        ref = new X();
        return ref;
    }

    public static void main(String args[]) {
        X x = new X();
        X x2 = fun(x);
        X x4 = new X();
        x2 = x4;
    }

}
Rajan saha Raju
  • 794
  • 7
  • 13
  • 1
    At what point? When you main is done, obviously all are GCed – Thiyagu Apr 05 '18 at 18:13
  • Just before done. – Rajan saha Raju Apr 05 '18 at 18:14
  • 1
    I don't believe Stack Overflow is the proper place for asking about puzzlers like this. These "how many objects are still referenced?" puzzlers have been asked and answered here more than enough times, and further replicas don't seem to add value to the site. Instead, study up on references & step through your code with a debugger. – Vince Apr 05 '18 at 18:39
  • 1
    The answer here could easily be zero with a clever JIT compiler seeing there is nothing to do, so I think this question is unanswerable as it depends far too much on the particular JVM the code is running under. – Ken Y-N Apr 06 '18 at 00:18

1 Answers1

2

There is 1 object eligible for Garbage Collection just before the main method ends.

Initially, you create one object:

X x = new X();  //One object on the heap assigned to 'x'

Then you call the 'fun' method which creates another object, this is returned and assigned to X2

X x2 = fun(x);  //Two objects on the heap one assigned to 'x' and one to 'x2'

Then, yet another is created and assigned to x4...

X x4 = new X(); //Three objects on heap, one assigned to 'x',  one assigned to 'x1', one to 'x4'

So, at this point, you have 3 different objects, but then you point x2 to the same object that x4 points to:

 x2 = x4;

That means you now have 1 object to which 2 variables are pointing. This leaves the 2nd object that was created, with no reference. This object is eligible for GC

Zippy
  • 3,826
  • 5
  • 43
  • 96