Java OCA OCP Practice Question 1894

Question

Assuming the file path referenced in the following class is accessible and able to be written, what is the output of the following program?

package mypkg; /*from w  w  w.  j  a  va  2s  .  c o  m*/
import java.io.*; 
public class Main { 
   public final static void main(String... inventory) throws Exception { 
      Writer w = new FileWriter("data.txt"); 
      try (BufferedWriter bw = new BufferedWriter(w)) { 
         bw.write("test!"); 
      } finally { 
         w.flush(); 
         w.close(); 
      } 
      System.out.print("Done!"); 
   } 
} 
  • A. Done!
  • B. The code does not compile for one reason.
  • C. The code does not compile for two reasons.
  • D. The code compiles but throws an exception at runtime.


D.

Note

The code compiles without issue, making Options B and C incorrect.

The BufferedWriter uses the existing FileWriter object as the low-level stream to write the file to disk.

By using the try-with-resources block, though, the BufferedWriter calls close() before executing any associated catch or finally blocks.

Since closing a high-level stream automatically closes the associated low-level stream, the w object is already closed by the time the finally block is executed.

The flush() command triggers an IOException at runtime, making Option D the correct answer.




PreviousNext

Related