nerdexam
Oracle

1Z0-809 · Question #47

Given the code fragment: public static void main (String[] args) throws IOException { BufferedReader bRcopy = null; try (BufferedReader bR = new BufferedReader (new FileReader ("employee.txt"))) {…

The correct answer is D. The code prints the content of the employee.txt file and throws an exception at line n3. Option D is correct because the try-with-resources block automatically closes bR when execution exits the try block - and since bRcopy holds a reference to the same underlying object, it too is closed. The file read and forEach print execute successfully before the block…

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?

Options

  • AA compilation error occurs at line n3.
  • BA compilation error occurs at line n1.
  • CA compilation error occurs at line n2.
  • DThe code prints the content of the employee.txt file and throws an exception at line n3.

How the community answered

(29 responses)
  • A
    3% (1)
  • B
    10% (3)
  • C
    14% (4)
  • D
    72% (21)

Explanation

Option D is correct because the try-with-resources block automatically closes bR when execution exits the try block - and since bRcopy holds a reference to the same underlying object, it too is closed. The file read and forEach print execute successfully before the block closes, so output is produced; then bRcopy.ready() at line n3 triggers the IOException described in the problem.

Lines n1, n2, and n3 all compile without error: BufferedReader implements AutoCloseable (valid for try-with-resources), assigning one BufferedReader reference to another is type-safe, and calling bRcopy.ready() is syntactically fine since the checked IOException is covered by the throws declaration on main. The distractors (A, B, C) all require a compilation error that doesn't exist.

Memory tip: Storing a try-with-resources variable in an outside reference does not escape the auto-close - think of try-with-resources as "close the object, not just the variable." Any alias pointing to the same resource is equally dead after the block ends.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice