Given:
1. class Bar { }
1. class Test {
2. Bar doBar() {
3. Bar b = new Bar();
4. return b;
5. }
6. public static void main (String args[]) {
7. Test t = new Test();
8. Bar newBar = t.doBar();
9. System.out.println("newBar");
10. newBar = new Bar();
11. System.out.println("finishing");
12. }
13. }
At what point is the Bar object, created on line 3, eligible for garbage collection?
A. After line 8.
B. After line 10.
C. After line 4, when doBar() completes.
D. After line 11, when main() completes.
Answer: D
Reference: http://java.sun.com/docs/books/tutorial/java/data/garbagecollection.html
According to sun the object will be eligible for garbage collection only when another objects
reference is passed to it since the original value is dropped or when the object is set to null
provided if all the reference of the object is dropped. In the above method the Bar object i.e b
created in line 3 is returned to main method where its value is not reset using another object or
it is not indirectly set to null thro another object so the object will be eligible for garbage
collection only after line 11, when main() completes.
Incorrect Answers:A. At line 8 a new Bar object is created but the object's reference is not made equal to b
object created at line 3 or b is not indirectly set to null value for being eligible for
garbage collection. thus this is not true.
B. At line 10 another Bar object is created but the object's reference is not made equal to
b object created at line 3 or b is not indirectly set to null value for being eligible for
garbage collection. thus this is not true.
C. After line 4 when doBar completes the method returns the value of object b created at
line 3 to the main method thus b is not eligible for garbage collection.最好大意翻译一下答案!