serialVersionUID is the only static field that gets serialized during object serialization.It basically represents the version of the class.
If we don’t declare it then the compiler throws the following warning:The serializable class SerializationExample does not declare a static final serialVersionUID field of type long.
If we don’t declare it, then during object serialization, a serialVersionUID is generated at run time and is also serialized.The dynamically generated serialVersionUID is a 64-bit hash of the class name, interface class names, methods and fields. For example:-6317291996449964275L.
What is the use of serialVersionUId?
When an object is serialized, the serialVersionUID is serialized along with the other contents.Later when the object is deserialized, the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class.If the numbers do not match then,
InvalidClassException is thrown.If the loaded class is not having a serialVersionUID declared, then it is automatically generated at runtime.
It is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected
InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value.
The serialVersionUID represents your class version, and you should increment it if the current version of your class is not backwards compatible with its previous version.