Serialization and Deserialization in java.

Serialization is the process of converting the state of an object into byte stream. De-serialization allow you to restore the serialized state into another instance of the same type. As you know, only the state of an object can serialized. Behavior is run-time phenomenon and it can’t be converted to a stream. Classes java.io.ObjectOutputStream and java.io.ObjectInputStream are provide necessary APIs to serialize and deserialize an object.

Serialization

In general, there are three steps involved in serializing a java object.

  1. Marking the class as Serializable
  2. Create an instance of ObjectOutputStream
  3. Use writeObject method of ObjectOutputStream to write the object into stream
Marking the class as Serializable

It just informs the compiler that this java class may be serialized. java.io.Serializable is a marker interface.

Create an instance of java.io.ObjectOutputStream

Write object to underlying output stream

Important API to serialize an object

Deserialization

Deserialization is process of restoring the serialized state of an object. In general, there are three steps involved in deserialization.

  1. Load the serialized state as stream
  2. Create an object of the java.io.ObjectInputStream with stream loaded in step one
  3. Read the object and cast to correct type
Load the serialized state as stream

Create an object of the ObjectInputStream with stream loaded in step one

Read the object and cast to correct type

Important API to Deserialize an object

Complete Example Code

One thought on “Serialization and Deserialization in java.