Java OCA OCP Practice Question 1906

Question

Which statement about the following program is true?

package mypkg; //from  www  .  j  av  a 2 s  .  co  m
import java.io.*; 
public class Main { 
   public void m() { 
      try(InputStream o = new ObjectInputStream(readBook())) { 
         while(o.read() != -1) { 
            System.out.println(o.read()); 
         } 
      } catch (Throwable t) { 
         throw new RuntimeException(t); 
      } 
   } 
   private InputStream readBook() throws IOException { 
      return new BufferedInputStream(new FileReader("magic.book")); 
   } 
   public static void main(String... horn) { 
      new Main().m(); 
   } 
} 
  • A. The code does not compile.
  • B. The program prints every byte in the file without throwing an exception.
  • C. The program prints every other byte in the file without throwing an exception.
  • D. The program throws an EOFException when the end of the file is reached.


A.

Note

The BufferedInputStream constructor in the readBook() method requires an InputStream as input.

Since FileReader does not inherit InputStream, the readBook() method does not compile, and Option A is the correct answer.

If FileReader was changed to FileInputStream, then the code would compile without issue.

Since read() is called twice per loop iteration, the program would print every other byte, making Option C correct.

Remember that InputStream read() returns -1 when the end of the stream is met.

We use EOFException with ObjectInputStream readObject() to determine when the end of the file has been reached.




PreviousNext

Related