Serialization in java


Sharing is caring!

Serialization in java provides a thing known as  object serialization.It means that an object can be represented as a sequence of bytes which includes object data as well as information about the object type and information of data stored in object.Classes ObjectInputStream and ObjectOutputStream are high level streams  which is defined for serializing and deserializing an object.

ObjectOutputStream Syntax:
public final void writeObject(Object x) throws IOException.

The above method serializes an object and sends it to the output stream.

ObjectInputStream Syntax:

public final Object readObject() throws IOException,ClassNotFoundException.

The above method retrieves the next object out of stream and deserializes it.


Here the class Employee implements the serializable interface.
Conditions needs to be met for successful serialization:

1.Class must implement the interface.
2.All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Serializing an object:

Here the above program is used to serialize an object.SerializeDemo instanties an employee object and serializes it to a file.After this program executed a file named employee.ser is created.It doesnt generate any output but it provides a file with .ser extension.

Deserializing an object

The above program provides the following result by deserializing the employee object

Deserialized Employee
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
: 0

Sharing is caring!