Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 88
Question ID: UKOCP27260
Given code:
- package com.udayankhattry.ocp;
- import java.io.*;
- import java.nio.file.Files;
- import java.nio.file.Paths;
- public class Test {
- public static void main(String[] args) throws IOException {
- /*INSERT*/
- }
- }
F: is accessible for reading and contains 'Book.java' file.
Which of the following statements, if used to replace /*INSERT*/, will successfully print contents of 'Book.java' on to the console?
Choose 3 options.
-
A
- Files.lines(Paths.get("F:\\Book.java"))
- .forEach(System.out::println);
-
B
- Files.lines(Paths.get("F:\\Book.java"))
- .stream()
- .forEach(System.out::println);
-
C
- Files.readAllLines(Paths.get("F:\\Book.java"))
- .forEach(System.out::println);
-
D
- Files.readAllLines(Paths.get("F:\\Book.java"))
- .stream()
- .forEach(System.out::println);
Reveal correct answers
Correct answers: A, C, D
Explanation
UKOCP27260:
Below are the declarations of lines and readAllLines methods from Files class:
public static Stream<String> lines(Path path) throws IOException {...}
public static List<String> readAllLines(Path path) throws IOException {...}
Files.lines(Paths.get("F:\\Book.java")) returns Stream<String> object. Hence forEach() can be invoked but stream() can't be invoked.
Files.readAllLines(Paths.get("F:\\Book.java")) returns List<String> object. Hence both forEach() and stream() methods can be invoked. List has both the methods. But converting list to stream() and then invoking forEach() method is not required but it is a legal syntax and prints the file contents.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
