SerialVersionUID is a constant that uniquely identifies for a serializable class. The JVM checks this constant during the deserialization process when an object is being constructed from an input stream. If the object being read has a serialVersionUID different than the one specified in the class, the JVM throws an InvalidClassException.
Note:-
SerialVersionUID is optional. That means the Java compiler will generate one if you don’t explicitly declare it.
Why should you declare a serialVersionUID explicitly?
The auto-generated serialVersionUID is calculated based on elements of the class: member variables, methods, constructors, etc. If one of these elements get change, the serialVersionUID will be changed as well.
For Example:-
- You wrote a program that stores some objects of the Student class to a file and the Student class doesn’t have a serialVersionUID explicitly declared.
- Later you update the Student class (e.g. added some methods/variables), and now the auto-generated serialVersionUID gets changed as well.
- Your program fails to deserialize because there serialVersionUID are different. The JVM throws an InvalidClassException.
That’s why it’s recommended to add a serialVersionUID explicitly for a serializable class.
nice blog..
LikeLike