< Prev
Next >


Process of Serialization and Deserialization.

Methods used in Serialization and Deserialization

The process of "serialization" and "deserialization" is performed using methods of two high level stream classes ObjectOutputStream and ObjectInputStream. These methods are -:

Methods Description
This method of ObjectOutputStream class , writes the state of the object to the stream, so that it can be saved in a file, thus performing serialization.

This method of ObjectInputStream class, reads the saved object out of the file in which object's state was saved, thus performing deserialization.


Program with Serialization and Deserialization :

import java.io.*;

class Serialz implements Serializable 	//implementing Serializable interface 
int i=0;
public static void main(String... ar)
Serialz ob= new Serialz();
ob.i=10;	//object instance variable's value set to 10
System.out.println("Before Serialization object has value : " + ob.i);
	FileOutputStream fos= new FileOutputStream("E:\\File.ser");//Saved state of the object is written to this file
	ObjectOutputStream oos= new ObjectOutputStream(fos);
	oos.writeObject(ob);		//Serializing, i.e. saving the state of this object, ob
catch(Exception exp)

	FileInputStream fis= new FileInputStream("E:\\File.ser"); //Reading the same file for Deserialization
	ObjectInputStream ois= new ObjectInputStream(fis);
	ob = (Serialz)ois.readObject();	//Deserializing, i.e. restoring the object to its original state.
	System.out.println("After Deserialization restored object has value : "+ ob.i);
catch(Exception exp)

}	//main method ends
}	//class definition ends

Output is -:

Before Serialization object has value : 10
After Deserialization restored object has value : 10

Program Analysis

In this code above, we are performing Serialization by calling the writeObject() method of ObjectOutputStream and saving the state of an object and its instance variable's value of int 10 in a file at path E:\\File.ser.

This serialized object is then deserialized by calling readObject() method of ObjectInputStream which reads the serialized saved object, using which the original object is reconstucted with its instance variable having the same value 10, which it had at the time of Serialization.

Note :

Method read() returns the serialized object contained in an object of Object class, which is a parent class of all Java classes. Hence, casting of this object to a type of original object is required to reconstruct the original object.

Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter

< Prev
Next >
< Console
Java transient keyword>

Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page


Please check our latest addition