Java OCA OCP Practice Question 1886

Question

Assume the file referenced in the Main class exists and contains data.

Which statement about the following class is correct?

package mypkg; /*from  w w w  .j  a va 2 s  . co m*/
import java.io.*; 
class Employee implements Serializable {} 
public class Main { 
   public static void main(String[] grades) { 
      try(ObjectInputStream ios = new ObjectInputStream( 
            new FileInputStream(new File("C://students.data")))) { 
         Employee record; 
         while((record = (Employee)ios.readObject()) != null) { 
            System.out.print(record); 
         } 
      } catch (EOFException e) { 
      } catch (Exception e) { 
         throw new RuntimeException(e); 
      } 
   } 
} 
  • A. The code does not compile.
  • B. The code compiles but prints an exception at runtime.
  • C. The program runs and prints all students in the file.
  • D. The program runs but may only print some students in the files.


D.

Note

The code compiles and runs without issue, so Options A and B are incorrect.

The problem is that checking if ios.readObject() is null is not the recommended way of iterating over an entire file.

The file could have been written with writeObject(null) in-between two non- null records.

In this case, the reading of the file would stop on this null value, before the end of the file has been reached.

Option D is the correct answer.

The valid way to iterate over all elements of a file using ObjectInputStream is to continue to call readObject() until an EOFException is thrown.




PreviousNext

Related