Question 1
The class below round-trips an object through `ObjectOutputStream` and `ObjectInputStream`, using a `ByteArrayOutputStream` as the in-memory transport. What is printed to standard output? ```java import java.io.*; public class Main implements Serializable { private static final long serialVersionUID = 1L; private String name; private transient int score; public Main(String name, int score) { this.name = name; this.score = score; } public static void main(String[] args) throws Exception { Main obj = new Main("Alice", 95); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); oos.close(); ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream(baos.toByteArray())); Main restored = (Main) ois.readObject(); ois.close(); System.out.println(restored.name + " " + restored.score); } } ```
A. Alice 95
Assumes `transient` is decorative and that `ObjectOutputStream` serializes every field regardless. In reality `transient` is an explicit instruction to the serialization mechanism to skip the field entirely; no bytes for `score` are ever written to the stream.
B. null 95
Reverses which field carries the `transient` modifier. It is `score` that is declared `transient` — not `name`. `name` is serialized and restored faithfully as `"Alice"`; `score` is the one that resets to its primitive default.
C. Alice 0Correct answer
`name` is a normal instance field, so `ObjectOutputStream` writes it and `ObjectInputStream` restores it as `"Alice"`. `score` is declared `transient`, so it is excluded from the stream; when the object is reconstructed `score` is never assigned by the stream and holds the JVM default for `int`, which is `0` (JLS §4.12.5). The result is `Alice 0`.
D. Throws `NotSerializableException` at runtime
`NotSerializableException` is thrown by `ObjectOutputStream` only when an object's class does not implement `java.io.Serializable`. `Main` explicitly declares `implements Serializable`, satisfying the contract, so the serialization round-trip completes without error.
Explanation
The Java serialization mechanism, governed by `ObjectOutputStream` and `ObjectInputStream`, writes and reads the non-static, non-transient fields of a `Serializable` class. A field marked `transient` is silently skipped during the write phase; no bytes for it appear in the stream. When `ObjectInputStream` reconstructs the object it allocates a new instance without calling the constructor and then populates only the fields present in the stream, leaving every `transient` field at its JVM-assigned default — `0` for `int`, `null` for reference types, `false` for `boolean` (JLS §4.12.5). The `serialVersionUID` field is a version tag used by the stream protocol to detect class-layout mismatches; it does not influence what is written or the default values restored.