Java SE 8 Programmer II — Question 8
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?
Answer options
- 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 employee.txt file and throws an exception at line n3.
Correct answer: D
Explanation
The correct answer is D because the code successfully prints the content of employee.txt as the BufferedReader is open during that operation. However, after the try-with-resources block completes, the BufferedReader is closed, and calling brCopy.ready() at line n3 results in an exception since brCopy references a closed BufferedReader. The other options are incorrect as there are no compilation errors in the relevant lines.