1Z0-811 · Question #64
Given the code fragment: List<String> names = new ArrayList<>(); names.add("Joel"); names.add("Paul"); names.remove(0); names.remove(0); System.out.println (names.isEmpty()); names.add ("Joel")…
The correct answer is B. true false. There appears to be an error in this question's answer key. The actual output of this code is true true, which is not among the listed choices. Here's the trace: add("Joel"), add("Paul") → list has 2 elements remove(0) twice → both elements removed, list is empty isEmpty() →…
Question
Options
- Afalse true
- Btrue false
- Cfalse false
- DA runtime exception is thrown
How the community answered
(28 responses)- A11% (3)
- B71% (20)
- C4% (1)
- D14% (4)
Explanation
There appears to be an error in this question's answer key. The actual output of this code is true true, which is not among the listed choices.
Here's the trace:
add("Joel"),add("Paul")→ list has 2 elementsremove(0)twice → both elements removed, list is emptyisEmpty()→trueadd("Joel"),add("Paul")→ list has 2 elements againclear()→ removes all elements, list is emptyisEmpty()→true
Why each option is wrong:
- A (
false true) - incorrect becauseremove(0)called twice on a 2-element list does empty it; the first print istrue, notfalse - B (
true false) - incorrect becauseclear()does empty the list;isEmpty()returnstrue, notfalse - C (
false false) - both removes are wrong for the same reasons - D (runtime exception) - no exception occurs; all operations are valid on an
ArrayList
Memory tip: remove(int index) removes by position, clear() nukes everything - both genuinely empty the list. isEmpty() always reflects the current state. If an exam question's "correct" answer contradicts this, flag it - the answer key has a bug.
The correct output is true true. If this is from a practice resource, the answer key is wrong.
Topics
Community Discussion
No community discussion yet for this question.