What is the output of the following application? Assume the file system is available and able to be written to and read from.
package mypkg; /*from ww w .j a va 2 s .co m*/ import java.io.*; public class Main { private int count = 1; private transient String value = "NONE"; { count = 2; } public Main() { this.count = 3; this.value = "Testing"; } public static void main(String... passengers) throws Exception { try (ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("ship.txt"))) { Main c = new Main(); c.count = 4; c.value = "Casino"; o.writeObject(c); } try (ObjectInputStream i = new ObjectInputStream(new FileInputStream("ship.txt"))) { Main c = i.readObject(); System.out.print(c.count + "," + c.value); } } }
E.
The readObject()
method returns an Object instance, which must be explicitly cast to Main in the second try-with-resources statement.
For this reason, the code does not compile, and Option E is the correct answer.
If the explicit cast was added, the code would compile but throw a NotSerializableException at runtime, since Main does not implement the Serializable interface.
If both of these issues were corrected, the code would run and print 4,null.
The value variable is marked transient, so it defaults to null when deserialized, while count is assigned the value it had when it was serialized.
Note that on deserialization, the constructors and instance initializers are not executed.