Marko Kitonjics Marko Kitonjics - 2 years ago 67
Java Question

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 (
) will be garbage collected, but I also know that
is not really the object, it's just a reference to it. So my answer was 5.

Is that correct? If not, then why?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download