Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 50
Question ID: UKOCP51352
F: is accessible for reading/writing and below is the directory structure for F:
- F:.
- └───A
- └───B
- Book.java
Book.java is a text file.
Given code of Test.java file:
- package com.udayankhattry.ocp;
- import java.io.IOException;
- import java.nio.file.*;
- public class Test {
- public static void main(String[] args) throws IOException{
- var src = Paths.get("F:\\A\\B\\Book.java");
- try(var reader = Files.newBufferedReader(src))
- {
- String str = null;
- while((str = reader.readLine()) != null) {
- System.out.println(str);
- }
- }
- }
- }
What will be the result of compiling and executing Test class?
- A Compilation error
- B Contents of Book.java are printed on to the console
- C An exception is thrown at runtime
Reveal correct answer
Correct answer: B
Explanation
UKOCP51352:
Variable 'src' infers to Path type and variable 'reader' infers to BufferedReader type.
Files class has methods such as newInputStream(...), newOutputStream(...), newBufferedReader(...) and newBufferedWriter(...) for files reading and writing.
Given code doesn't cause any compilation error.
As Book.java is a text file and accessible, hence its contents are printed on to the console.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
