7

I don't know exactly where to use default serialVersionUID or generated serialVersionUID in java ?

private static final long serialVersionUID = 4125965356358329466L; // generated
private static final long serialVersionUID = 1L; // default
1

3 Answers 3

5

The Serial Version ID is used in serializing and deserializing an object. Java identifies if the bytes you want to deserialize match the local class version,if not it will throw an exception. This is important when doing RMI or persisting object structures. The serialization runtime associates with each serializable class a version number, 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.

1
  • 3
    I understood what is verison id but what is the difference between those two? May 24, 2019 at 6:33
5

If you do not provide a serialVersionUID yourself for a Serializable class, then Java generates one for you based on the details of that class. Some IDEs and other tools can perform the same computation to enable you to explicitly put that generated serialVersionUID into your class. It is useful to do this if you want to make changes to the class while maintaining serialization compatibility with the old version -- a somewhat tricky endeavor in most cases, but often doable.

If you're managing the serialVersionUID manually, on the other hand, then it is a lot easier to use an ordinary serial number, starting at 1 (or some other number you choose) and being incremented whenever the class is changed in a way that breaks serialization compatibility. If you're going to bother with this, though, then do make sure to do it properly -- that is, change the serialVersionUID when appropriate -- otherwise you defeat the whole purpose.

2
  • 1
    Depending on the default id generation exposes you to differences in implementations; you will have to know for sure that serializer and deserializer use the same provider/version of JVM.
    – Jan Larsen
    Feb 2, 2017 at 8:07
  • Not so, @JanLarsen. The algorithm for computing the default serialVersionUID is standardized. As the docs for java.io.Serializable put it, "If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification" (emphasis added). In particular, see docs.oracle.com/javase/7/docs/platform/serialization/spec/…. Feb 2, 2017 at 13:54
0

There is no practical difference. As long as you change (increment) the number when you change the class, you will be ok.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.