Java OCA OCP Practice Question 2269

Question

Given this code segment (assume that necessary import statements are provided in the program that contains this code segment).

Stream<String> lines = Files.lines (Paths.get ("./text.txt"))
// line n1

If a file named text.txt exists in the current directory in which you are running this code segment, which one of the following statements will result in printing the first line of the file's contents?.

  • A. lines.limit(1).forEach(System.out::println);
  • B. lines.forEach(System.out::println);
  • C. lines.println();
  • D. lines.limit(1).println();
  • e. lines.forEach(1);


A.

Note

the limit(1) method truncates the result to one line; and the forEach() method, when passed with the System.out::println method reference, prints that line to the console.

Option B prints all the lines in the given file and thus is the wrong answer.

the code segments given in the other three options will result in compiler errors.




PreviousNext

Related