nerdexam
Oracle

1Z0-819 · Question #96

Given: public static void main(String[] args) { try { Reader reader1 = new FileReader("File1.txt"); Reader reader2 = new FileReader("File2.txt"); Reader reader3 = new FileReader("File3.txt"); }…

The correct answer is A. All three readers are still open. All three FileReader objects are open at Line 1 because the code uses a regular try block, not a try-with-resources block - there is no close() call anywhere, and no exception was thrown (all files exist), so the catch block never executes. Options B, C, and D are all wrong for…

Java I/O API

Question

Given: public static void main(String[] args) { try { Reader reader1 = new FileReader("File1.txt"); Reader reader2 = new FileReader("File2.txt"); Reader reader3 = new FileReader("File3.txt"); } catch (IOException ex) { logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } // Line 1 System.out.println("Done"); } When run and all three files exist, what is the state of each reader on Line 1?

Options

  • AAll three readers are still open.
  • BAll three readers have been closed.
  • COnly reader1 is closed.
  • DOnly reader1 has been closed

How the community answered

(27 responses)
  • A
    74% (20)
  • B
    7% (2)
  • C
    4% (1)
  • D
    15% (4)

Explanation

All three FileReader objects are open at Line 1 because the code uses a regular try block, not a try-with-resources block - there is no close() call anywhere, and no exception was thrown (all files exist), so the catch block never executes. Options B, C, and D are all wrong for the same core reason: nothing in this code ever closes any reader - not implicitly, not explicitly. Distractors C and D likely tempt candidates who mistakenly think a failed FileReader constructor (e.g., file not found) would close previously-opened readers, but that only affects the reader that threw; and in this scenario, no exception is thrown at all. The memory tip: if the keyword try is immediately followed by a parenthesized resource declaration (try (Reader r = ...)), Java auto-closes it - if there are no parentheses after try, you are responsible for closing manually, and if you don't, resources stay open.

Topics

#resource management#FileReader#exception handling#try-catch

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice