Given the code fragment:

class Student{
    String name;
    int age;
}

And,

public class Test{
    public static void main(String[] args){
        Student s1 = new Student();
        Student s2 = new Student();
        Student s3 = new Student();
        s1 = s3;
        s3= s2;
        s2 = null;
    }
}

Which statement is true?

A. After line 8, three objects are eligible for garbage collection
B. After line 8, two objects are eligible for garbage collection
C. After line 8, one object is eligible for garbage collection
D. After line 8, none of the objects are eligible for garbage collection

题解

在这里按照顺序把实体化出来的 Student 对象标记为 A,B,C。程序运行完第 8 行时,A 对象已经没有被任何变量参考,B 对象被 s3 变量参考,C 对象被 s1 变量参考。没有被任何变量参考的 A 对象会在稍后被垃圾回收(Garbage Collection)。