1Z0-829 · Question #20
Given the code fragments: class Car implements Serializable { private static long serialVersionUID = 454l; String name; public Car(String name) { this.name = name; } public String toString() {…
The correct answer is F. At line n2, in the main method signature, add throws IOException, ClassNotFoundException. Option F is correct because ObjectInputStream.readObject() throws two checked exceptions - IOException and ClassNotFoundException - that must either be caught or declared in the method signature; without this declaration, the code fails to compile entirely, so no output is…
Question
Options
- AAt line n1, implement the java.io.Serializable interface.
- BAt line n3, replace readObject () with readline().
- CAt line n3, replace Car with LuxuryCar.
- DAt line n1, implement the java.io.AutoCloseable interface
- EAt line n2, in the main method signature, add throws IOException, ClassCastException.
- FAt line n2, in the main method signature, add throws IOException, ClassNotFoundException.
How the community answered
(48 responses)- A19% (9)
- B4% (2)
- C8% (4)
- D2% (1)
- F67% (32)
Explanation
Option F is correct because ObjectInputStream.readObject() throws two checked exceptions - IOException and ClassNotFoundException - that must either be caught or declared in the method signature; without this declaration, the code fails to compile entirely, so no output is possible. Option E looks tempting but substitutes ClassCastException, which is an unchecked RuntimeException that never needs to be declared - the distinguishing word on the exam is "Cast" vs. "NotFound". Options A and D are irrelevant to the problem: LuxuryCar already inherits Serializable from Car, and AutoCloseable is only needed for try-with-resources, not serialization. Option B is wrong because readLine() reads raw text, not deserialized objects - only readObject() can reconstruct a serialized Java object. Option C (casting to LuxuryCar) doesn't fix the compilation error caused by the undeclared checked exceptions, so it can't produce any output on its own.
Memory tip: "When you serialize, Java must find the class to rebuild it - that's why it throws ClassNotFoundException, not ClassCastException." The "Not Found" signals a missing class definition on the classpath at deserialization time.
Topics
Community Discussion
No community discussion yet for this question.