0
votes

So I've recently been to job interview and was asked the following question. (Actually it was just a test writing, so I couldn't ask any questions)

At the end of the main method, how many objects will be eligible for garbage collection?

public class Main {
    public static void main(String[] args) {
        Object obj;
        for (int i = 0; i < 5; i++) {
            obj = new Object();
        }
        obj = null;
    }
}

(A) 0

(B) 1

(C) 5

I know it's 0 because at least one object (obj) will be garbage collected, but I also know that obj is not really the object, it's just a reference to it. So my answer was 5.

Is that correct? If not, then why?

2
wow.. too many bullets on single line.. btw 5 is right answer - sidgate
its so easy man. It should be Five. but it must me mentioned at which line too?? - Vikrant Kashyap

2 Answers

6
votes

Your answer 5 is correct.

Here total 5 number of objects are created through for loop and all of these will be eligible for garbage collection at the end of the method.

4
votes

Probably 0,

The compiler might workout some optimisation and eliminate the entire loop and avoid creating the five objects created in the loop in the first place.

So if no compiler optimisation is going on, 5 objects are created inside the loop and their references is being overwritten in the variable obj, at the end variable will reference the last object which is being assigned to null.