nerdexam
Oracle

1Z0-809 · Question #117

Given the code fragment: Path file = Paths.get ("courses.txt"); // line n1 Assume the courses.txt is accessible. Which code fragment can be inserted at line n1 to enable the code to print the…

The correct answer is B. Stream<String> fc = Files.readAllLines (file); fc.forEach (s -> System.out.println(s)). Option B as stated does not actually compile - this question contains an error in the answer key. Files.readAllLines(Path) returns List<String>, not Stream<String>, so assigning it to Stream<String> fc causes a type mismatch at compile time. Option C is the genuinely correct…

Question

Given the code fragment: Path file = Paths.get ("courses.txt"); // line n1 Assume the courses.txt is accessible. Which code fragment can be inserted at line n1 to enable the code to print the content of the courses.txt file?

Options

  • AList<String> s = Files.list(file); fc.stream().forEach (s -> System.out.println(s));
  • BStream<String> fc = Files.readAllLines (file); fc.forEach (s -> System.out.println(s));
  • CList<String> fc = Files.readAllLines (file); fc.stream().forEach (s -> System.out.println(s));
  • DStream<String> fc = Files.list (file); fc.forEach (s -> System.out.println(s));

How the community answered

(24 responses)
  • A
    13% (3)
  • B
    75% (18)
  • C
    8% (2)
  • D
    4% (1)

Explanation

Option B as stated does not actually compile - this question contains an error in the answer key. Files.readAllLines(Path) returns List<String>, not Stream<String>, so assigning it to Stream<String> fc causes a type mismatch at compile time. Option C is the genuinely correct answer: it correctly assigns Files.readAllLines(file) to List<String> fc, then calls .stream().forEach() to print each line.

Why each distractor fails:

  • A - Files.list(Path) returns Stream<Path> (directory entries, not file lines), not List<String>; additionally the code references undeclared variable fc after declaring s.
  • B - Files.readAllLines() returns List<String>, not Stream<String> - this is a compile-time type mismatch.
  • D - Files.list(Path) lists directory contents as Stream<Path>, not file lines as Stream<String>; using it on a regular file to read text content is semantically and type-incorrect.

Memory tip: Link the method name to its return type - readAll**Lines** ends with the plural noun, so it returns a List; Files.lines() (the streaming variant) returns a Stream<String>. When you see Stream<String> on the left-hand side, the right-hand side must call Files.lines(), not Files.readAllLines().

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice