serialVersionUID
TL;DR
serialVersionUIDis a unique version identifier assigned to a Serializable class.- It is used during deserialization to verify that the sender and receiver have compatible versions of the class.
- If you modify a class structure and the IDs don’t match, the JVM throws an
InvalidClassException.
Concept
Imagine you serialize a User object (which has String name and int age) and save it to a database.
A month later, you update your Java code. You delete int age and add LocalDate dateOfBirth.
You then query the database and try to deserialize the old byte stream into your new User class.
The JVM needs to know if the byte stream is compatible with the current class. It does this using the serialVersionUID.
When you serialize an object, the JVM writes the class’s serialVersionUID into the byte stream. When you deserialize it, the JVM compares the ID in the bytes to the ID in the current .class file. If they match, it proceeds. If they are different, it crashes immediately to prevent data corruption.
Examples
import java.io.Serializable;
public class Employee implements Serializable {
// Explicitly defining the version ID.
// If you change the class structure in a breaking way, you MUST increment this number.
private static final long serialVersionUID = 2L;
private String name;
private String department;
// ...
}
Interview Questions
Q: What is serialVersionUID?
A: Answer…
Q: What happens if you don’t define a serialVersionUID explicitly?
A: If you don’t define one, the Java Compiler will automatically generate a random cryptographic hash based on the exact structure of the class (method names, fields, access modifiers).
This is incredibly dangerous! If you change anything (even making a private method public, which doesn’t affect data), the compiler will generate a brand new hash. All objects previously serialized to your database will instantly become unreadable, throwing InvalidClassException. You should always explicitly declare the serialVersionUID.
Q: Is it possible to deserialize an object if the serialVersionUID matches, but the fields have changed?
A: Yes! If the IDs match, Java will attempt a “Best Effort” restoration.
- If the old byte stream has an
agefield, but the new class doesn’t, the JVM safely ignores theagedata. - If the new class expects a
dateOfBirthfield, but the old byte stream doesn’t have it, the JVM initializesdateOfBirthtonull.
This is why manually maintaining theserialVersionUIDallows for backward-compatible class evolution.