Java Serialization

tutorial and example
tutorial and example

JAVA SERIALIZATION

Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object’s data, object’s type and datatypes of members in that objects.

We can write that object in a file and then it can be read and deserialized.

We retrieve the information from bytes and can recreate the object in the memory.

The most powerful feature is that the whole process is independent from JVM. This means that an object can be serialized form one machine and can be deserialized to another machine.

ObjectInputStream and ObjectOutputStream contains the methods for serialization and deserialization.

Important methods are:

The above method serializes an Object and then sends it to the output stream. Similarly, the ObjectInputStream class has  the method for deserializing an object

This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so we will need to cast it to its appropriate datatype.

The class that implements  java.io.Serializable interface can be serialized and those fields which are marked transient cannot be serialized.

Example:

Person Class

Employee Class

Main Class

Output:

The readObject method may throw a ClassNotFoundException so we have to insert in try/catch block. JVM have to find the bytecode for the class in order to deserialize an object. If JVM can’t find a class during the deserialization of an object the ClassNotFoundException is thrown.