If the serialVersionUID of a class changes after an object has been serialized, Java treats the new class version as incompatible with the serialized object. During deserialization, the JVM compares the serialVersionUID stored in the object stream with the serialVersionUID of the current class. If they do not match, deserialization fails and an InvalidClassException is thrown.
Key Points: • serialVersionUID is used to verify class compatibility during deserialization. • A mismatch indicates that the class definition has changed in an incompatible way. • The JVM prevents deserialization to avoid data corruption or inconsistent object states. • An InvalidClassException is thrown when the serialVersionUID values differ. • Explicitly defining serialVersionUID helps control compatibility across class versions.
Example: Assume an Employee object is serialized when the class has:
private static final long serialVersionUID = 1L;
Later, the class is modified and the value is changed to:
private static final long serialVersionUID = 2L;
When Java attempts to deserialize the previously stored object, it detects the version mismatch and rejects the operation.
Code Example:
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
}Later changed to:
public class Employee implements Serializable {
private static final long serialVersionUID = 2L;
private int id;
private String name;
}Result:
java.io.InvalidClassException: Employee; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2
Why Does Java Do This?
• Prevents incompatible objects from being loaded • Protects application stability • Maintains data integrity • Avoids unexpected runtime errors caused by structural class changes
Common Scenarios Causing Mismatches:
• Changing serialVersionUID manually • Removing important fields • Modifying class hierarchy • Allowing Java to generate serialVersionUID automatically and then changing the class structure
Best Practice:
Always declare serialVersionUID explicitly in Serializable classes to maintain control over version compatibility and avoid unexpected deserialization failures.
Interview Tip: A concise interview answer is:
"If the serialVersionUID changes between serialization and deserialization, Java considers the class versions incompatible and throws an InvalidClassException. This mechanism protects the application from loading objects whose structure may no longer match the current class definition."