7.4 Serialization Fundamentals & the serialVersionUID Contract
← Back to Chapter 7: Garbage Collection & Serialization
Serialization transforms an in-memory Java object graph into a flat sequence of binary bytes for disk persistence or transmission over a network socket. Deserialization reconstructs that live object graph from the byte stream.
What is Serialization?
Serialization means converting a Java object into a format that can be stored or transferred.
Think of it like this:
Java Object
↓
Serialization
↓
Bytes
↓
Store / Send over Network
Later, we can convert those bytes back into the original Java object.
Bytes
↓
Deserialization
↓
Java Object
Why do we need Serialization?
There are mainly two common reasons.
1. Store an object
For example, you want to save an object into a file.
Java Object → Bytes → File
2. Transfer an object
For example, one Java application needs to send object data to another system.
Application A
↓
Object
↓
Serialization
↓
Network
↓
Deserialization
↓
Application B
How do we serialize an object?
Java provides: Serializable
It's a marker interface, meaning it doesn't contain any methods and thus it doesn't require you to implement any methods.
Example:
import java.io.Serializable;
class Employee implements Serializable {
// Serializable tells Java that objects of this class
// are allowed to be serialized.
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
}
Then Java's serialization APIs can serialize the object.
Writing and Reading Streams
// Serialization
try (var oos = new ObjectOutputStream(new FileOutputStream("session.ser"))) {
oos.writeObject(new UserSession("user_101", "ADMIN"));
}
// Deserialization
try (var ois = new ObjectInputStream(new FileInputStream("session.ser"))) {
UserSession session = (UserSession) ois.readObject();
}
What is serialVersionUID?
You can define:
private static final long serialVersionUID = 1L;
Example:
class Employee implements Serializable {
// Used to verify that the serialized object
// and current class version are compatible.
private static final long serialVersionUID = 1L;
private String name;
private int age;
}
Think of it as a version number for the serialized class.
Object saved with version 1
↓
Class changed
↓
Still compatible?
↓
serialVersionUID helps JVM check this
If the versions don't match, you can get:
InvalidClassException