OCP Question 40, Explanation

Given the code fragment:

public static void main (String[] args) throws IOException {
    BufferedReader brCopy = null;
    try (BufferedReader br = new BufferedReader(new FileReader("derby.log"))) { //line n1
        br.lines().forEach(x -> System.out.println(x));
        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 derby.log is accessible and contains valid text. What is the result?

A. A compilation error occurs at line n3.
B. A compilation error occurs at line n1.
C. A compilation error occurs at line n2.
D. The code prints the content of the derby.log file and throws an exception at line n3.


The correct answer is D.


There are no reasons for this code to fail compilation: the br object on line n1 is built correctly, line n2 is merely an assignment, and the ready() method does exist in BufferedReader. Therefore, all that remains is just option D. What’s interesting, the Problem itself tells us why the code throws an RTE: any resource opened via a try-with-resources construct gets closed at the end of the try block, which makes brCopy on line n3 point to a closed stream.

Leave Comment

Your email address will not be published.