Serialization And Deserialization In Java

Updated: May 30


Introduction


Serialization in Java is the process of converting the state of an object into a byte stream; deserialization in java is the opposite process where serialized byte stream would be converted back into the object.


The mechanism is platform-independent, objects serialized in one platform can be deserialized in an entirely different platform enabling us to save the byte stream into a disk or transfer them over the network.

Serializable Interface


Java objects that need to be serialized must implement the java.io.Serializable interface. The interface is a marker interface so one does not have to implement any specific methods.


Below is an example of a serializable class named Car. Note that during serialization static and fields marked as transient are ignored.

ObjectOutputStream and ObjectInputStream


Support to serialize is provided using the writeObject(Object o) in the java.io.ObjectOutputStream class. The method takes a serializable object and converts it into a sequence (stream) of bytes.

Similarly, support to deserialize is provided using the readObject() method in the java.io.ObjectInputStream class. The method can read a stream of bytes and convert it back into a Java object.

Serialization and Deserialization


In the below code we try to serialize and deserialize an object of the class Car. We can observe from the output that the price of the car is set to 0 after deserialization since it was marked transient.

Serial Version UID


Each serializable class is associated with a version number called serialVersionUID, this is used to check compatibility between the sender and receiver of the serialized object.


If the receiver has loaded a class different from what the sender had used this will result in an InvalidClassException.


A serializable class can declare its own serialVersionUID and must match the below format, If not specified then at runtime serialization will calculate a default value based on the class specification.

Most modern IDEs support the generation of serialVersionUID.


While we review and upload more content for you, we would love to hear your feedback.