What is serialVersionUID ?
The serialVersionUID is an identifier for serialized objects. If the serialVersionUID of a serialized object doesn't match to the current serialVersionUID of that class, then the deserialization throws an InvalidClassException.
Here is one example, we have a customer class which is having the default serilVersionUID
Let us serialize this object
Now change the serialVersionUID in the customer class and try to Deseralize
private static final long serialVersionUID = 2L;
java.io.InvalidClassException: com.vinod.test.Customer; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2
To avoid this casting exception we have to keep the same serialVersionUID for serializable objects and de-serialization will be successfull. If we are not adding this version uid JVM will generate add the default id for each objects and it is possible to do the serialization and de-serialization but after the serialization is there any changes happened in the serializable class then it will throw the Invalid cast exception during de-serialization (Objects wont match)
eg: If i am adding below phone number details to Customer class after the serialization and it will throw the invalid cast exception while de-serialization (if we have same serialVersionUID over there in the class it wont throw exception)