Serialization and DeSerialization in Java

In this tutorial, we will learn about Serialization and DeSerialization in Java.

It is known that an Object has a state and behavior. Behavior is associated with class but the state of an object is associated with an individual object.

In day to day life we deal with objects and want to save the state of an object. Java provides a mechanism for this and it is called as Serialization.

Serialization is the process of writing the state of an object to a byte stream so that the byte stream can be reverted back into a copy of the object. This is useful when you want to save the state of your object to a persistent storage area, such as a file. A Java object is serializable if its class or any of its super classes implements either the java.io.Serializable interface or its sub-interface java.io.Externalizable. java.io.Serializable is a marker interface and it doesn’t have any methods in it.

Conditions for Serialization of an Object:

  • Class must implement the java.io.Serializable interface.
  • All the fields of the Class must be serializable.

Let’s see the serialization of an object with an example. Let’s create a Car.java class which implements java.io.Serializable.

Car.java:

Now create a SerializationDemo.java class.

SerializationDemo.java:

Here we have used ObjectOutputStream class. The DeSerializationDemo.javaclass contains writeObject() method for serializing an Object.

Well done ! You have serialized an object.

What if we want to get the original object back. This can be achieved by using DeSerialization in java.

DeSerialization in java:

DeSerialization is the reverse process of Serialization to get the original object back. Let’s see this with an example.

Let’s create DeSerializationDemo.java class.

DeSerializationDemo.java:

Here we have used ObjectInputStreamObjectInputStream class contains readObject() method for deserializing an object.

Let’s check the output.

Output:

Now you have successfully retrieved the original object.

Other Tutorials:

Cloning in Java

Reflection in Java

Related posts

Leave a Comment