Gem Wang wrote:The right answer is BD. I understand B. But for D, why two is eligible on line 9 instead of line 11. One line 10, two is still be used.
Anyone can explain this please?
The best way to solve this kind of questions (on the mock and actual exams) is to make a little drawing: reference variables on the left, objects on the right and you draw arrows between reference variables and objects based on the code snippet. If a reference variable is set to null, you delete/remove all outgoing arrows from that reference variable. All objects which don't have an arrow anymore are unreachable and thus eligible for GC. In this forum you'll find plenty of drawings to better understand the code snippets. Examples
here,
here and
here. And you'll get a pencil and paper (or equivalent, e.g. erasable pen and small whiteboard) on the actual exam, so you can definitely use the same technique when it matters as well.
Please note the reference variable is completely different from the object it is referring to. So on
line3 you'll have a reference variable
one (of type
Rabbit) and a new object (created by invoking the
new operator:
new Rabbit()). So options A, B, and C are about the object (created by the
new operator),
not the reference variable
one. The same applies of course to
line4: reference variable
two and another new object (created by invoking the
new operator:
new Rabbit()). And options D, E, and F are about the object (created by the
new operator),
not the reference variable
two.
Hope it helps!
Kind regards,
Roel
PS. Always use code tags when posting code to the forums. Unformatted or unindented code is extremely hard to read and many people that might be able to help you will just move along to posts that are easier to read. Please click this link ⇒
UseCodeTags ⇐ for more information. Properly indented and formatted code greatly increases the probability that your question will get quicker, better answers. Jeanne already added the code tags for you. See how much easier the code is to read?