Serialization and Deserialization Example

Serialization and Deserialization Example thumbnail
9K
By Dhiraj 21 October, 2016

Serialization is a mechanism provided by java to save the state of one or more objects. During serialization, an object is represented as a sequence of bytes which holds the object and all of its instance variables. And once the object is serialized, whenever required it can be again deserialized to retain the object again with the exact same state in memory. Serialization and deserialization is JVM independent and hence an object can be serialized at one platform and the same object can be retained at another platform with the same state.

Serialization and Deserialization Details

  • Java serialization mechanism takes care of serializing complete object graph. For example if Department class has any instance varible of let say Employee than Employee class object will also be serialized given that Employee class also implements Serializable. If not, we get a runtime exception as java.io.NotSerializableExcetion.
  • Again if you do not want to serialize Employee object or you don't have control over the Employee Object then it must be declared as a Transient variable during its declaration in Department class.
  • If a parent class does not implements Serializable interface and child class implements Serializable then serializing a child class will never throw an exception and child class will be serialized. In this case, any instance variable that is inherited in the child class will be reset to the default values.
  • If a superclass is Serializable, then all subclasses of that class automatically implements Serializable implicitly.
  • Serialization only applies to Objects and hence static variables are never serialized as static variables are purely class variables.
  • Constructor of object is never called when an object is deserialized.
 Other Interesting Posts
Hello World Java Program Breakup
Convert HashMap to List in Java
Sorting HashMap by Key and Value in Java
Why wait(),notify(),notifyAll() defined in object class in Java
How to use Comparable and Comparator in Java with Example

ObjectOutputStream and ObjectInputStream

ObjectOutputStream and ObjectInputStream are considered to be higher classes in the java.io packages as we already know the lower-level classes , such as java.io.FileOutputStream and java.io.FileInputStream. The mechanism of the basic serialization happens with just two methods one to serialize objects and write them to a stream, and a second to read the stream and deserialize objects.

ObjectOutputStream.writeObject()      //serialze and write
ObjectInputStream.readObject()        //read and deserialize

Here the Department class implements the Serializable interface. Serializable is a marker interface;it has no methods to impement. It is only used to indicate something to compiler or JVM.

Department.java
import java.io.*;

public class Department implements Serializable {}

Following is the implementation of class which will really serialize and deserialize the Department Object.The invocation of writeObject() will serialize the object and then also writes the serialized object to a file. Similarly, invocation of readObject() returns an Object, that's why we need to cast it to the Department object.

SerializeDept.java
public class SerializeDept {
	public static void main(String[] args) {
		Department dept = new Department();
		try {
			FileOutputStream fs = new FileOutputStream("serializedDept.txt");
			ObjectOutputStream os = new ObjectOutputStream(fs);
			os.writeObject(c);
			os.close();
		}	catch(Exception e) { e.printStackTrace();}
		
		try {
			FileInputStream fis = new FileInputStream("serializedDept.txt");
			ObjectInputStream ois = new ObjectInputStream(fis);
			c = (Cat) ois.readObject();
			ois.close();
		}   catch (Exception e) { e.printStackTrace(); }
	}
}

Deserialization Steps

  • All instance variables are assigned to their default values.
  • The constructor is invoked, which immdiately invokes the superclass constructor.
  • Instance variables that are instantiated as part of their declaration are assigned their initial value.
  • The constructor completes.
  • Conclusion

    I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.

Further Reading on Core Java