Java | Benefits of declaring SerialVersionUID in your code

Author - Rita

SerialVersionUID is a class invariant that is used to validate that the classes on both sides of the wire are the same. During Serialization it marshals an object and sends it over the stream. During marshalling process, the SerialVersionUID is also transferred over the wire. The receiving process (Deserialization) compares the SerialVersionUID that were sent over the wire with the SerialVersionUID of local classes. If they aren’t equal, system will throw UnmarshallException and the method call will never reach your code on server.

The serialization process provides a version number to each class during serialization, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If you will change the serialVersionUID of a class, then during deserialization you will get an InvalidClassException due to serialVersionUID mismatch.

If we don’t specify SerialVersionUID, we can face two problems :

1. If we don’t specify SerialVersionUId for our classes, it will be generated at runtime which
is very expensive.
2.  Second serious problem is that at runtime SerialVersionUID is generated via hashing all
fields and member of the class and hence extraordinarily sensitive to minor changes.

So as a best practice if you have the need to transfer your classes via stream, always define
SerialVersionUID inside your classes as below :

public abstract class AbstractEntity implements Serializable {
		private static final long serialVersionUID = 1L;

A serializable class can declare its own serialVersionUID explicitly by declaring a field named “serialVersionUID” that must be static, final, and of type long. You should always avoid to use default values. IL is the default value but it is not compulsory to use it always. As it is of long type, you can use any valid long value for serialVersionUID field.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published.