nerdexam
Oracle

1Z0-809 · Question #142

Given the code fragment: ``java public static void main(String[] args) { String[] arr = {"A", "B", "C", "D", "you"}; List<String> arrList = new ArrayList<>(Arrays.asList(arr)); if (arrList.removeIf(…

The correct answer is B. Compilation fails. Option B is correct because the variable s is scoped exclusively to the lambda body - it is a parameter of the lambda expression (String s) -> { return s.length() < 2; } and cannot be referenced in the enclosing if block's body where System.out.println(s + " removed") appears…

Question

Given the code fragment:
public static void main(String[] args) {
 String[] arr = {"A", "B", "C", "D", "you"};
 List<String> arrList = new ArrayList<>(Arrays.asList(arr));
 if (arrList.removeIf( (String s) -> { return s.length() < 2; } )) {
 System.out.println(s + " removed");
 }
}
What is the result?

Options

  • AHi removed
  • BCompilation fails.
  • CAn UnsupportedOperationException is thrown at runtime.
  • DThe program compiles, but it prints nothing.

How the community answered

(31 responses)
  • A
    10% (3)
  • B
    81% (25)
  • C
    3% (1)
  • D
    6% (2)

Explanation

Option B is correct because the variable s is scoped exclusively to the lambda body - it is a parameter of the lambda expression (String s) -> { return s.length() < 2; } and cannot be referenced in the enclosing if block's body where System.out.println(s + " removed") appears. The compiler sees s as undefined in that outer scope and refuses to compile.

Why the distractors fail:

  • A ("Hi removed"): Not only does "Hi" not appear in the list, but the code never compiles in the first place.
  • C (UnsupportedOperationException): ArrayList fully supports removeIf() - that exception would only apply to unmodifiable collections (e.g., the fixed-size list returned by Arrays.asList() directly, without wrapping it in new ArrayList<>()).
  • D (prints nothing): The program never reaches runtime, so it can't silently do nothing - it stops at compile time.

Memory tip: Think of a lambda's parameters like a local variable inside a method - they die when the lambda closes its brace. If you need the removed value outside the lambda, you must capture it in a separate variable before calling removeIf, or use an iterator-based approach instead.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice