Serialization in Java with Example

By | October 28, 2015

Serialization in Java is the process of converting an object into bytes stream to save it in file. Or we can say that, serialization is used to persist (save) the state of an object.

The process of recreating object from bytes stream is called deserialization.

Below I have mentioned few applications of serialization in Java.

Uses of Serialization

To persist the state of an object for future use.
To send an object on network.
To store user session in web based applications.

Serialization in Java with Example

Image Source

To serialize an object, its class must implement Serializable interface.

Serializable interface does not have any member and so it is called as marker interface. It tells the Java compiler that the object is serializable.

To make some data members non serializable, we must declare them as transient.

ObjectOutputStream and ObjectInputSteam are two classes that contain methods to serialize and deserialize an object.

writeObject() method of ObjectOutputStream class is used to write an object to file.

readObject() method of ObjectInputStream class is used to read an object from file.

It is a Java convention to give .ser extension to the file in which we are saving the object.


Lets take one example to understand how serialization and deserialization is done in Java.


Serialization and Deserialization Example




You can see in above output that value of age variable is 0, which is the default value of integer type variable. This shows that transient data members can’t be serialized. You must also note in above code that when we read the object from file it must be type casted into corresponding class type.

Below I have added a video that will help you to learn concept of serialization in Java. If you found anything incorrect or have any doubts regarding above tutorial then feel free to ask by commenting below.

Leave a Reply

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