Is this the only variable eligible for garbage collection?


I have a question on eligibility of garbage collection for this piece of code.

public static void main(String[] args) {
    Object a = new Object();
    Object b = new Object();
    Object c = new Object();
    a = b;
    b = c;
    c = null;

I've read through a couple examples of Java garbage collection and I think I'm getting the hang of it. So what I was thinking is that after the line c = null; only c will be eligible for garbage collection because it's the only object that has discarded all references to it. Am I right here?


In Java, variables are not eligible for garbage collection; objects are. Variables hold references to objects but are not the objects themselves.

Let's look at your example with some sample object IDs (the internal identifiers the JVM uses to keep track of them, and not ordinarily visible):

Object a = new Object(); // id=1
Object b = new Object(); // id=2
Object c = new Object(); // id=3

You now have objects 1, 2, and 3, each referenced from a single variable: a:1, b:2, c:3. When you copy those references between variables, here's what the state looks like:

a = b;    // a:2, b:2, c:3
b = c;    // a:2, b:3, c:3
c = null; // a:2, b:3, c:null

After a = b, you've lost all references to object 1, which was originally in a, and so it immediately becomes eligible for garbage collection. Objects 2 and 3 are still reachable until the end of the block, where all of the variables fall out of scope together.