What’s the significance of serialVersionUID

By | April 20, 2014

The serialVersionUID is used as a version control in a Serializable class. JVM uses it to compare the versions of the class ensuring that the same class was used during Serialization is loaded during Deserialization. If you do not explicitly declare a serialVersionUID, JVM will do it for you automatically, based on various aspects of your Serializable class.The default serialVersionUID computation is highly sensitive to class details and may vary from different JVM implementation, and result in an unexpected InvalidClassExceptions during the deserialization process.

Lets understand this using an example
1.Person.java
This class implements serializable.

2. SerializePerson.java
This class serialize an object of Person class storing it as “person.ser”

3.DeserializePerson.java
This class Deserializes an object of Person class reading it from “person.ser”

Compiling and running the above classes in sequence will give you this output

Which is correct.

Modify serialVersionUID
Go to the Person class and change serialVersionUID to 2L. Compile Person.java . Now try to read the same person object from “person.ser” by running DeserializePerson.class file.You will get this error :

The InvalidClassException came, because we are trying to write a serialization class with serialVersionUID=1L but trying to retrieve it back with updated serialization class, serialVersionUID=2L.

Leave a Reply

Your email address will not be published. Required fields are marked *