Serialization in Java

Java provides a mechanism called Serialization nothing but conevrting Java object as a stream of bytes which includes the object’s data as well as information about the object’s type and the types of data stored in the object.

By using Serialization mechanism we can persist the object state in file or DB,the reverse mechanism i.e reading the object state from source is called as Deserialization.

How to make a Java class Serializable?

The Java class which we want to make Serializable just needs to implements interface
and JVM will take care of serializing object.Serializable interface exists in package.
It doesn’t have any method and also called Marker Interface. When the Java class implements
interface it becomes Serializable in Java and gives compiler an indication that use Java Serialization mechanism to serialize this object.

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

The above method from ObjectOutputStream which is used to serializes an Object

The above method from ObjectInputStream which is used to deserializes an Object

let us have a small example which will explain how to Serialize and DeSerialize  “AccountHolder” object.

Let us have a look  in the below code , how to serialize “AccountHolder” object which is saved in accountHolder.txt


Let us have a look  in the below code , how to deserialize “AccountHolder” object, i.e reading object state from accountHolder.txt.


 Rules during Serialization Process:

1.  Static data member in a class will not be serialized because static is the part of class not object, that is the reason Gender value is printed as null  in above example

 2.  Transient variables are not serialized and persisted and during deserialization those value are initialized with there default value   which is zero in case of int variable, that is the reason Mobile Number is set to “0” in above example.


Posted in Java IO and tagged , , , , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">