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)。