Java OCA OCP Practice Question 1870

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  ww  w . j av  a2 s. c o m
import java.io.*; 
public class Main { 
   public void sendAlert(File fn) { 
      try(BufferedWriter w = new BufferedWriter(new FileOutputStream(fn))) { 
         w.write("ALERT!"); 
         w.flush(); 
         w.write('!'); 
         System.out.print("1"); 
      } catch (IOException e) { 
         System.out.print("2"); 
      } finally { 
         System.out.print("3"); 
      } 
   } 
   public static void main(String[] testSignal) { 
      new Main().sendAlert(new File("mypkg.txt")); 
   } 
} 
  • A. 3
  • B. 13
  • C. 23
  • D. The code does not compile.


D.

Note

BufferedWriter is a wrapper class that requires an instance of Writer to operate on.

In the Main class, a FileOutputStream is passed, which does not inherit Writer, causing the class not to compile, and making Option D the correct answer.

If FileWriter was used instead of FileOutputStream, the code would compile without issue and print 13, making Option B the correct answer.




PreviousNext

Related