Java OCA OCP Practice Question 457

Question

What happens when you try to compile and run the following application?

 1. import java.io.*; 
 2. /*from w ww . j ava  2 s .co m*/
 3. public class MyClass {  
 4.   public static void main(String[] args) { 
 5.     try { 
 6.       File f = new File("xxx.ser"); 
 7.       FileOutputStream fos = new FileOutputStream(f); 
 8.       ObjectOutputStream oos = new ObjectOutputStream(fos); 
 9.       oos.writeObject(new Object()); 
10.       oos.close(); 
11.       fos.close(); 
12.     } 
13.     catch (Exception x) { } 
14.   } 
15. } 
  • A. Compiler error at line 9.
  • B. An exception is thrown at line 9.
  • C. An exception is thrown at line 10.
  • D. No compiler error and no exception.


B.

Note

The writeObject() method is declared to take an Object argument.

At runtime, there is a precondition check to make sure the argument implements Serializable, which Object doesn't do.




PreviousNext

Related