Memra

Serialization: Serializable, ObjectStreams & serialVersionUID

Turning objects into bytes (and back) — and why you rarely use this directly today.

Java serialization basics

Java's built-in serialization writes the state of an object graph to a byte stream and reads it back:

// A serializable class
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private String username;
    private transient String password;  // NOT serialized
}

Serializable is a marker interface — no methods to implement. The JVM performs the read/write automatically using reflection.

Writing:

try (ObjectOutputStream oos = new ObjectOutputStream(
        new FileOutputStream("user.ser"))) {
    oos.writeObject(new User("alice", "secret"));
}

Reading:

try (ObjectInputStream ois = new ObjectInputStream(
        new FileInputStream("user.ser"))) {
    User u = (User) ois.readObject();  // unchecked cast
}

serialVersionUID: when you deserialise, the JVM checks this long against the serialVersionUID of the loaded class. If they differ (because the class changed between writing and reading), it throws InvalidClassException. Declaring it explicitly prevents the JVM from auto-generating a brittle, compiler-version-dependent value.

transient fields are skipped during serialisation — their values are lost. The deserialised object gets the field's default value (null, 0, false).

In practice: direct Java serialization is fragile and a known security risk. Production applications use JSON (Jackson, Gson) or Protocol Buffers instead. The exam expects you to know the API and the pitfalls; real job code reaches for a library.

NORMAL ~/memra/learn/java-from-zero/serialization utf-8 LF