How does Serialization work?
Step 1: Implement Serializable
For a class to support serialization, it must implement the java.io.Serializable interface.
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;
// constructor, getters, setters
}
Step 2: Use ObjectOutputStream to Serialize
You can serialize an object like this:
Person person = new Person("John", 30);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
oos.writeObject(person);
}
This writes the object’s state into a file called person.ser.
Step 3: Use ObjectInputStream to Deserialize
Later, you can read the object back:
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
Person person = (Person) ois.readObject();
System.out.println(person.getName() + " is " + person.getAge());
}
🧩 Important: What gets serialized?
- All non-
transientfields get serialized. staticfields are NOT serialized (because they belong to the class, not the object).- Transient fields are skipped (that’s the point of
transient).
🔥 What is serialVersionUID and why is it important for versioning?
serialVersionUID is a special constant that acts like a version number for the class. It helps during deserialization.
private static final long serialVersionUID = 1L;
Why do you need it?
Serialization saves the exact structure of a class. When you deserialize, Java compares the saved version (from the file) with the current class version.
- If they match (same
serialVersionUID), deserialization succeeds. - If they don’t match, deserialization fails with an
InvalidClassException.
What happens if you don’t define serialVersionUID?
Java will generate one automatically based on the class structure (fields, methods, etc.). This is risky because:
- Even a tiny change (like renaming a field) will generate a different
serialVersionUID. - This makes older serialized objects incompatible with newer versions of the class.
Recommended Practice
- Always explicitly define
serialVersionUIDif you expect the class to be serialized and deserialized in future versions of your app. - This gives you control over versioning and lets you evolve the class safely.
Example with serialVersionUID
public class Person implements Serializable {
private static final long serialVersionUID = 1L; // fixed version
private String name;
private int age;
// constructor, getters, setters
}
Summary Table
| Term | Meaning |
|---|---|
| Serialization | Convert object → byte stream |
| Deserialization | Convert byte stream → object |
| serialVersionUID | Class version identifier to handle compatibility |
| transient | Skip field during serialization |
Final Thought: What happens if you change a class?
If you:
- Add a new field (like
address), old serialized files won’t have that field. - If you set
serialVersionUIDcorrectly, you can manually handle the missing data (provide a default value inreadObject()method if needed).