nerdexam
Oracle

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() →…

Arrays and Logic

Question

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"); names.add ("Paul"); names.clear(); System.out.println (names.isEmpty ()); What is the result?

Options

  • Afalse true
  • Btrue false
  • Cfalse false
  • DA runtime exception is thrown

How the community answered

(28 responses)
  • A
    11% (3)
  • B
    71% (20)
  • C
    4% (1)
  • D
    14% (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 elements
  • remove(0) twice → both elements removed, list is empty
  • isEmpty()true
  • add("Joel"), add("Paul") → list has 2 elements again
  • clear() → removes all elements, list is empty
  • isEmpty()true

Why each option is wrong:

  • A (false true) - incorrect because remove(0) called twice on a 2-element list does empty it; the first print is true, not false
  • B (true false) - incorrect because clear() does empty the list; isEmpty() returns true, not false
  • 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

#ArrayList operations#remove() and clear() methods#code execution tracing#isEmpty() behavior

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice