What is Serialization and Deserialization in Java

Learn Serialization and Deserialization in Java with real use cases, advantages, and disadvantages.

Abhishek Kumar
5 min readMay 16, 2024

Agenda of this article

  1. Introduction.
  2. What is Serialization?
  3. How to Serialize the object of a class.
  4. Advantages of Serialization.
  5. What is Deserialization?
  6. How to Deserialize the stream of bytes into objects of class.
  7. How to secure credentials using transient keyword, during the Deserialization process.
  8. Difference between Serialization and Deserialization in Java.
  9. Some pointers for implementation of Serializable interface.
  10. Summary of the article.

Introduction

Before diving much into Serialization, Let’s understand the need for Serialization.

Suppose you have a big office chair, now you want to carry it somewhere, here you have 2 choices either you carry the chair in its present state or fold and carry the chair you will choose the 2nd option. in this context process of folding the chair into smaller pieces is known as serialization and the reverse of that is known as Deserialization. We can save some space in our luggage store.

What is Serialization?

The mechanism of converting an object state into a byte stream to store them in some storage is known as Serialization.

How to serialize the object of a class.

To serialize an object of a class, the class must have the behavior of serializable. We can achieve this with the help of a serializable marker interface in Java (an interface having no methods known as marker interface) which is part java.io.Serializable;

public class Student implements Serializable {
int id;
String name;

public Student(int id, String name) {
this.id = id;
this.name = name;
}
}

Now class Student is Serializable.

Let's make the object of class student serialized.

To make the object serialized we have a class called ObjectOutputStream in java.

  1. ObjectOutputStream — Class helps us to write the object into the stream.
  2. The constructor of this class accepts the parameter of OutputStream.

Methods available in this class —

  1. writeObject(Object o) — Serialises the object & writes to ObjectOutputStream, object must support io.Serializable interface.
  2. flush() — flush the current stream.
  3. close() — Close the current stream.
 public void makeSerializable() {
try {
Student student = new Student(10, "Abhishek");

// Creating file stream
FileOutputStream fout = new FileOutputStream("localFile.txt");

// writing the object
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(student);
out.flush();
out.close();
System.out.println("Object Serialized Successfully!");
} catch (Exception ex) {
System.out.println(ex.toString());
}
}

Note — Here we have used the file system to store the serialized objects.

Advantages of Serialization.

  1. Cost Saving — We can store the serialized objects in the db with lesser space wrt to the original objects and can be retrieved easily at any point in time.
  2. Time-Saving — Creating an object takes way more time than converting the byte stream into an object.
  3. Platform Independent — Serialized objects in one OS can be deserialized in another.
  4. Object Cloning — It makes the process of cloning simple. Can create the exact copy by deserializing the serialized objects.

What is Deserialization?

The mechanism of converting a stream of bytes back into the object is known as Deserialization. It is the reverse process of Serialization.

Deserialization of an object from the byte of stream.

How to Deserialize the stream of bytes into objects of class.

For Deserializing the serialized objects back into a stream of bytes. Java provides us with internal implementation in ObjectInputStream to achieve the deserialization. The constructor of this class accepts the parameter of type InputStream.

Methods available in this class —

  1. readObject() — Reads the object from the input stream or converts the byte stream back into the object.
  2. close() — This method closes the input stream.
public void deserializable(){
try {
// creating the stream to read the input object
FileInputStream fis = new FileInputStream("localFile.txt") ;
ObjectInputStream ois = new ObjectInputStream(fis);

Student st = (Student)ois.readObject() ;
System.out.println("Deserializing the stream into the student object:- Id: " + st.id + " Name: " + st.name);
}
catch(Exception ex){
System.out.println(ex.toString());
}
}

Transient Keyword

There should be a question — what if I have some credentials in my object, will that also be part of the serialized object? if it is then those will be reached to the receiver, which is not good.

Solution — We have the transient keyword in Java which hides the data to reach the receiver. If data is transient then that will not be serialized.

public class Student implements Serializable {
int id;
String name;
transient int var = 10; // not getting serialized

public Student(int id, String name) {
this.id = id;
this.name = name;
}
}

Difference between Serialization and Deserialization

Serialization 
=======================
1. It is the mechanism of converting an object to a stream of bytes.
2. It helps to write byte stream into storage(file, database, inMemory..)
3. we can achieve this with the help of ObjectOutputStream class in Java.

DeSerialization
=======================
1. Deserialization helps to convert the stream of objects to the original state of the object.
2. It helps to read byte stream from storage(file, database, inMemory..)
3. we can achieve this with the help of ObjectInputStream class in Java.

Some pointers for implementation of Serializable interface.

  1. If a parent class has already implemented the serializable interface, a child class is not needed to implement again.
  2. Any static data member can’t be serialized, Otherwise, NotSerializableException will be thrown.
  3. A static method can’t be used during deserialization, as the static method is on a class level not on an instance.
  4. While deserialization(converting the bytes of the stream into an object), the constructor of objects is not called.
  5. All associated objects must have to implement the Serializable interface.

Summary

  1. Serialization is the process of converting the objects into a byte stream.
  2. Deserialization is the process of converting the bytes stream back into the objects.
  3. Any static method or fields can’t be used for serialization.
  4. In an Is-A relationship child does not implement the Serializable interface, in the HAS-A relationship, both classes must implement the Serializable interface.

Thank you for reading this article till the end, I hope it added some value to your skills. Please upvote and provide your feedback.

--

--

Abhishek Kumar
Abhishek Kumar

Written by Abhishek Kumar

Software Engineer at OpenText India, Loves to write articles on the technology related to JAVA, Spring Boot, Solidity, RESTful API, Spring Security.

Responses (1)