1

Q: 02 Given:

11. public void genNumbers() {
12.    ArrayList numbers = new ArrayList();
13.    for (int i=0; i<10; i++) {
14.       int value = i * ((int) Math.random());
15.       Integer intObj = new Integer(value);
16.       numbers.add(intObj);
17.    }
18.    System.out.println(numbers);
19. }

Which line of code marks the earliest point that an object referenced by intObj becomes a candidate for garbage collection?

A. Line 16
B. Line 17
C. Line 18
D. Line 19
E. The object is NOT a candidate for garbage collection.

Answer: D

Confused why answer is D not B. Please help me understand.

1
  • Why do you think it's B? Commented Jul 11, 2013 at 11:27

4 Answers 4

8

You probably think since the variables lifetime is ended at the end of the block, the object can be removed by the garbage collector. But since that object was added to the list numbers, it is still referenced. Therefore it's after the lifetime of numbers ends and the list can also be removed by the garbage collector.

Sign up to request clarification or add additional context in comments.

Comments

1

At line 17, the variable intObj goes out of scope, but this does only mean that there is one less reference to the Integer object than before. The numbersarray still references the same object as intObj did, so it cannot be collected before numbers goes out of scope.

Comments

1

the object id garbage collected only when it is nolonger reachable by any reference. but in our example the new Integer(value); becomes out of rechable tointObj but it is accessed by arraylist so we still access the new Integer(value); so it becomes garbage collected only when arraylist becomes out of scope.

Comments

0

The object intObj is created at line 15, and a reference to it is added to numbers in line 16. While intObj goes out of scope at line 17, it is still referenced by numbers, which does not go out of scope until line 19.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.