Serialization and Deserialization in Java

Generally all applications require objects to be saved. Once a program is executed/terminated, the object is destroyed by itself. If you want to persist the state of an object you can use the serialization concept by converting data into a byte stream.

Serialization means to convert state of an object into a byte stream. Deserialization is the process of converting the serialized form of an object back into a copy of the object. The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform. Serialization can be used in cases like saving the state of an object to a file or sending the object across a network.

A Java object is serializable if its class or any of its superclass implements either java.io.Serializable interface or its subinterface, java.io.Externalizable. Serializable is a marker interface.

If we try to serialize a non-serializable object then we will get java.io.NotSerializableException which is a runtime exception.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.

Java platform specifies default mechanism by which objects are serialized. However, a Java class can override this default serialization and define its own way of serialization.
During serialization, information that identifies its class is recorded in the serialized stream but the ‘class file’ itself is not recorded. It is the responsibility of the deserializing system to load the necessary files.

If an object to be serialized refers to other objects then those other objects must be serialized at the same time. When an object is serialized, all of the objects that are reachable from that object are serialized as well.