“What’s a serialVersionUID used for?”
“What if you do not define it?”
These seem to be pretty popular Java interview questions. The second one builds on the top of the first. But, what’s more popular than these questions are the blog posts explaining what the right answer is.
Here’s the gist: serialVersionUID is used to track the version of an object. Each JVM, when serializing an object, by uses this field to version it. When deserializing this object, the JVM then references the version again, to check if the objects are of the same class, and if the version does not match, throws up the InvalidClassException.
In what case is there a version mismatch? When you do not define the serialVersionUID, and the JVM compiler implementation differs. For example: Oracle JDK vs Amazon Corretto JDK. The autogenerated serialVersionUID may have different values.
The intention of using in the same serialVersionUID is that when a class changes, the version should be kept intact to allow for backward compatibility.
Fair, this is correct. But what these blogs fail to mention, and the interviewers fail to question is, why would you use Java serialization in the current age?
If the intention is backward compatibility amongst different JVMs, there are better encodings available - JSON, Protobuf, etc.
Over the network transfer and serialization in most modern apps has been taken over by these encodings. It’s human-readable, inherently backward compatible (for adding/removing fields, not modifying fields), for plain serialization and deserialization at the very least.
The most underrated part - these encodings can be used to test APIs. Imagine trying to create a Java Serialized object to test a simple API with Postman.
Most APIs now use JSON, and if you indeed want to version it, you can, without breaking the backward compatibility! No going over the hoops to learn the why’s and when’s to use serialVersionUID.
Want to read more on Java Serialization? Look up these links: