Are static variables serialized in Serialization process

serialVersionUID is special and is not subject to these rules. There is code within the serialization machinery that specifically handles this field to perform the automatic version checks.


  1. Instance Variables: These variables are serialized, so during deserialization we will get back the serialized state.

  2. Static Variables: These variables are not serialized, So during deserialization static variable value will loaded from the class.(Current value will be loaded.)

  3. transient Variables: transient variables are not serialized, so during deserialization those variables will be initialized with corresponding default values (ex: for objects null, int 0).

  4. Super class variables: If super class also implemented Serializable interface then those variables will be serialized, otherwise it won't serialize the super class variables. and while deserializing, JVM will run default constructor in super class and populates the default values. Same thing will happen for all superclasses.


serialVersionUID is a special static variable used by the serialization and deserialization process, to verify that a local class is compatible with the class used to serialize an object. It's not just a static variable as others, which are definitely not serialized.

When an object of a class is first serialized, a class descriptor containing among other things the class name and serial version UID is written to the stream. When this is deserialized, the JVM checks if the serial version UID read from the stream is the same as the one of the local class. If they're not, it doesn't even try to deserialize the object, because it knows the classes are incompatible.


The serialVersionUID is also serialized in this case.

Any static variable that is provided a value during class initialization is serialized.

However in normal cases, where you would provide the value to a static variable at the main class / run-time would not be serialized.

You can try to access the serialVersionUID by making it public and try to access it after deserialization.

You can refer "http://javabeginnerstutorial.com/core-java-tutorial/transient-vs-static-variable-java/" for more information.

Hope that helps. Cheers !!

Tags:

Java