Java SE 8 Programmer II Exam Question

What is the result?

Question

Given the code fragment: public static void main (String[] args) throws IOException{ BufferedReader brCopy = null; try (BufferedReader br = new BufferedReader (new FileReader("employee.txt"))) { // line n1 br.lines().forEach(c -> System.out.println(c)); brCopy = br;//line n2 } brCopy.ready();//line n3; } Assume that the ready method of the BufferedReader, when called on a closed BufferedReader, throws an exception, and employee.txt is accessible and contains valid text.

What is the result?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

D.

The given code fragment reads the content of a text file named "employee.txt" using a BufferedReader object and prints it to the console using the forEach method of the Stream returned by the lines method of the BufferedReader.

Let's analyze the code line by line:

java
BufferedReader brCopy = null;

Declares a BufferedReader object named brCopy and initializes it with null.

java
try (BufferedReader br = new BufferedReader (new FileReader("employee.txt"))) { br.lines().forEach(c -> System.out.println(c)); brCopy = br; }

Declares and initializes a BufferedReader object named br to read from the file "employee.txt" using a FileReader. The try-with-resources statement is used to ensure that the BufferedReader is closed after the try block is executed. The forEach method of the Stream returned by the lines method of the BufferedReader prints each line of the file to the console. The brCopy variable is assigned the value of the br variable so that it can be used outside the try block.

java
brCopy.ready();

Calls the ready method of the brCopy object. This method returns a boolean indicating whether the next read operation on the stream will block. If the BufferedReader is closed, a IOException is thrown.

Based on the code analysis, the correct answer is (D) The code prints the content of the employee.txt file and throws an exception at line n3.

The code correctly reads the content of the file and prints it to the console. However, since the br object is closed at the end of the try block, the brCopy object is also closed. Therefore, calling the ready method on the brCopy object will result in an IOException being thrown at line n3.