nerdexam
Oracle

1Z0-809 · Question #214

Given the code fragment: `` List<String> valList = Arrays.asList("","George", "", "John", "Jim"); Long newVal = valList.stream() // line n1 .filter(x -> !x.isEmpty()) .count(); // line n2…

The correct answer is A. A compilation error occurs at line n2. The provided answer key appears to contain an error. This code actually compiles and runs successfully, printing 3 - neither choice A nor B is correct. Here's what actually happens: valList.stream() at line n1 creates a Stream<String> with no issue. .filter(x -> !x.isEmpty())…

Question

Given the code fragment:
List<String> valList = Arrays.asList("","George", "", "John", "Jim");
Long newVal = valList.stream() // line n1
 .filter(x -> !x.isEmpty())
 .count(); // line n2
System.out.print(newVal);
What is the result?

Options

  • AA compilation error occurs at line n2.
  • BA compilation error occurs at line n1.

How the community answered

(41 responses)
  • A
    80% (33)
  • B
    20% (8)

Explanation

The provided answer key appears to contain an error. This code actually compiles and runs successfully, printing 3 - neither choice A nor B is correct.

Here's what actually happens:

  • valList.stream() at line n1 creates a Stream<String> with no issue.
  • .filter(x -> !x.isEmpty()) removes the two empty strings, leaving "George", "John", and "Jim".
  • .count() at line n2 returns a long primitive (3L), which is automatically autoboxed to Long - a valid assignment since Java 5. No compilation error occurs here.
  • System.out.print(newVal) prints 3.

Both choices describe compilation errors that don't actually happen. The real answer - "prints 3" - isn't among the options shown.

If this came from a practice test: double-check the source, as the answer key is likely wrong for this question. The key exam concept to remember is that Stream.count() returns long (primitive), which autoboxes cleanly into Long (wrapper) - no cast or explicit conversion needed.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice