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
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)- A13% (3)
- B75% (18)
- C8% (2)
- D4% (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)returnsStream<Path>(directory entries, not file lines), notList<String>; additionally the code references undeclared variablefcafter declarings. - B -
Files.readAllLines()returnsList<String>, notStream<String>- this is a compile-time type mismatch. - D -
Files.list(Path)lists directory contents asStream<Path>, not file lines asStream<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.