Java Serialization and Deserialization with Example

In this topic, we will learn what are Serialization and Deserialization with examples in Java. Serialization is a process to convert the state of an object into a byte stream. This process helps to store or save a byte stream into the hard disk or socket, file or send over the network. Deserialization is a process to convert a byte stream into an actual Java object. This process helps to retrieve a Java object from the byte stream that can be stored on the hard disk or socket, file or sent over the network.              
java_serialization_deserialization                              

The created byte stream is platform-independent. So, an object is serialized in one platform and deserialized on the other platform. To create a serializable Java object we need to implement the java.io.Serializable interface.
The ObjectOutputStream class contains the writeObject(Object obj) method to make serializing the object.

public final void writeObject(Object obj)throws IOException

The ObjectInputStream class contains the readObject() method to make deserialise the object.

public final Object readObject()throws IOException, ClassNotFoundException

Advantages of Java Serialization

   • To save/persist the state of an object in Java
   • To travel an object across the network in Java

The objects of those classes can be serialized which is implementing Serializable Interface in Java. Serializable is a marker Interface in Java. It has no data member and method. It is used to mark Java classes so the objects of these classes may get some specific capability automatically.

Important points to remember for Serializable

   • A parent class is implemented a Serializable interface then a child class is not mandatory to implement a Serializable interface and vice-versa is not true.
   • The non-static data members of the class are saved through the serialization process.
   • Static data members and transient data members are not participating in the serialization process. If we want to not save a non-static data member so we can make it transient.

SerialVersionUID

The runtime associates a version number with each Serializable class called a SerialVersionUID. This version number is used while the Deserialization process to verify that the sender and receiver of a serialized object have loaded classes for that object which are compatible with respect to the serialization. In case the deserialization object is different than the serialization then it throws InvalidClassException. It is declared as a private static final long variable in Java. If it is not declared explicitly then at the runtime will calculate a default serialVersionUID value for that class based on various aspects of the class.

Example of Serialization and Deserialization

In this example, we will serialize the object of the Person class and write the data of the person into a file through serialization and read data from that file through deserialization.  
Example 1:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Person implements Serializable {
public int id;
public String name;
Person(int id, String name) {
this.id = id;
this.name = name;
    }
}
class Test {
public static void main(String[] args) {
Person p = new Person(1, "Peter");
String filename = "G:\\person.txt";
//Serialization Process
try {
//saving of person object into the file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
//method for serialization of an object
out.writeObject(p);
out.close();
file.close();
System.out.println("Object has been serialized successfully");
System.out.println("Id = " + p.id);
System.out.println("Name = " + p.name);
}
catch (IOException ex) {
System.out.println("IOException is caught");
}
Person p2 = null;
//Deserialization Process
try {
//reading a person object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
//method for deserialization of an object
p2 = (Person) in.readObject();
in.close();
file.close();
System.out.println("Object has been deserialized successfully");
System.out.println("Id = " + p2.id);
System.out.println("Name = " + p2.name);
}
catch (IOException ex) {
System.out.println("IOException is caught");
}
catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException is caught");
    }
  }
}

Output

Object has been serialized successfully
Id = 1
Name = Peter
Object has been deserialized successfully
Id = 1
Name = Peter

Example 2:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Person implements Serializable {
private static final long serialVersionUID = 1393L;
transient int a;
static int b;
String name;
int age;
public Person(String name, int age, int a, int b1) {
this.name = name;
this.age = age;
this.a = a;
b = b1;
  }
}
public class Test {
public static void printData(Person p) {
System.out.println("name = " + p.name);
System.out.println("age = " + p.age);
System.out.println("a = " + p.a);
System.out.println("b = " + p.b);
}
public static void main(String[] args) {
Person p = new Person("ABC", 20, 2, 1000);
String filename = "G:\\person.txt";
//Serialization
try {
//saving of object of the person in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
//method for serialization of object
out.writeObject(p);
out.close();
file.close();
System.out.println("Object has been serialized\n" + "Data before Deserialization.");
printData(p);
//value of static variable changed
p.b = 2000;
} catch (IOException ex) {
System.out.println("IOException is caught");
}
p = null;
//Deserialization
try {
//reading of object of the person from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
//method for deserialization of object
p = (Person) in.readObject();
in.close();
file.close();
System.out.println("Object has been deserialized\n" + "Data after Deserialization.");
printData(p);
} catch (IOException ex) {
System.out.println("IOException is caught");
}catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException" + " is caught");
  }
 }
}

Output

Object has been serialized
Data before Deserialization.
name = ABC
age = 20
a = 2
b = 1000
Object has been deserialized
Data after Deserialization.
name = ABC
age = 20
a = 0
b = 2000

→ In the above we have seen during the deserialization process of an object values of a and b are changed. That’s why because a was declared transient and b was declared static.

Conclusion

In this topic, we learnt about Java Serialization and Deserialization with examples.

Leave a Comment