Marko Kitonjics
Marko Kitonjics

Reputation: 257

How many objects will be eligible for garbage collection?

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?

Upvotes: 0

Views: 203

Answers (2)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23349

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.

Upvotes: 4

Vimal Bera
Vimal Bera

Reputation: 10497

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.

Upvotes: 6

Related Questions