Serialization & Deserialization in Detail with All Interview Questions

Tanveer
6 min readSep 3, 2022

--

Serialization and Deserialization are concepts in java that seem difficult to everyone and that makes us hesitate to learn, so here I will explain the the concept in easiest form with real-life examples and I will avoid using jargon words that make us confused while learning the concept, My motive is to make you understand all the concept used in serialization and deserialization along with all the interview questions that can appear in your interview.

In this article, we will cover the below questions

a) Serialization & Deserialization

b) Transient vs static vs final Keywords in Serialization

c) Object Graph in Serialization

d) Customised Serialization

e) Serialization with respect to inheritance

f) Externalization vs Serialization

g) SerialVersion UID

1. What are Serialization and Deserialization?

Serialization in Java allows us to convert an Object to a stream that we can send over the network or save it as a file or store in DB for later usage. Deserialization is the process of converting the Object stream to actual Java objects to be used in our program.

example: Let’s understand it with a practical example,

Assume you live in a small city and your son or daughter or some other children who live in a different city and they have asked you to send a Big big balloon, so you go to market and see the big ballon filled with air which you liked and you want to send this ballon to their city since you can not send the balloon filled with air rather you will remove the air from the balloon and send the package along with balloon pump so this process of converting your balloon in such a form where someone can carry it over the network/courier know as serialization, Upon receiving the balloon kids can refill it with air with the help of balloon pump and convert it into usable form a so this process of converting back to actual state is known as Deserialization

example code,

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 SerializeDeserializeExample implements Serializable {
int i = 100;
int j = 200;
}

public class main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
SerializeDeserializeExample serializeDeserializeExample = new SerializeDeserializeExample();
//process of serialization
FileOutputStream fos = new FileOutputStream("example.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(serializeDeserializeExample);

//process of Deserialization
FileInputStream fis = new FileInputStream("example.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
SerializeDeserializeExample deserializeExample = (SerializeDeserializeExample) ois.readObject();
System.out.println(deserializeExample.i + "\n" + deserializeExample.j);
/*
100
200
*/

}
}

Points to be Remember :

a) We can serialize only serializable object

b) An object is said to be serializable only if it implements a serializable interface, serializable is a marker interface

c) If we try to serialize a non-serializable object then we will get a run time exception as NotSerializableException

Some Followup questions

Q. Is it possible to serialize more than one object?

Ans. yes, it is possible to serialize more than one object but we must deserialize in the same order if the order is not maintained we will face a class cast exception.

Q. what if we don’t know the order of objects in serialization?

Ans. we can use the parent class as a reference. (use of inheritance every class inherits an Object so we can use the object class to retrieve and later cast it to a respective object using an instance of a keyword)(let me know in the comments if you need an example)

2. Transient vs static vs final Keywords in Serialization

What is Transient Keyword: Transient is a modifier which is applicable to only variables, At the time of serialization if we don’t want any variable to be part of the serialization process we should declare that particular variable as transient , for example, transient int i = 100; at the time of serialization JVM ignores the value of transient keyword and by default value would ve saved. Transient means not to serialize

Static vs Transient : Static variables are not part of object state hence anyways they won’t participate in serialization hence declaring them as transient doesn’t make sense at all

Final vs Transient: Final variables will be participated directly by their values hence there is no impact of declaring them as transient

3. Object Graph In Serialization

An Object graph is whenever we are serializing any object then all the set of objects will be serialized which are reachable from that object also if any object which is reachable and it does not implements a serializable interface it will throw run time exception as NotSerializableException

For example, ObjectGraphA is called in SerializeDeserializeExample and ObjectGraphB is called in ObjectGraphA

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 SerializeDeserializeExample implements Serializable {
ObjectGraphA objectGraphA = new ObjectGraphA();

}

class ObjectGraphA implements Serializable {
ObjectGraphB objectGraphB = new ObjectGraphB();
}

class ObjectGraphB implements Serializable {
int j = 200;
}

public class main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
SerializeDeserializeExample serializeDeserializeExample = new SerializeDeserializeExample();
//process of serialization
FileOutputStream fos = new FileOutputStream("objGraph.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(serializeDeserializeExample);

//process of Deserialization
FileInputStream fis = new FileInputStream("objGraph.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
SerializeDeserializeExample deserializeExample = (SerializeDeserializeExample) ois.readObject();
System.out.println(deserializeExample.objectGraphA.objectGraphB.j);
/*
200
*/

}
}

4. Customised Serialization

What is Customised serialization?

before that let’s understand why we need it, we declare transient keyword to hide the sensitive data, for example, passwords and other sensitive data we can’t send directly over the network hence we declare them as transient and in the previous example, we have seen if we declare any variable as transient, while deserialization we can’t recover the actual value of that variable and we get default value as output, so to access that information(loss information due to transient keyword) we need customized serialization,

To retrieve this information we need to do some extra layer of work on the sender as well as receiver side known as customized serialization

Real-life example: Let’s say I want to send money to a different city and assume I don’t have the flexibility of online transfer hence I need to send the cash with somebody because I can’t travel since it is money or gold nobody would take responsibility to carry these amounts because of security purpose, instead what I will do is I will wrap the money in some paper and put in a cartoon of mango I will make sure there is 2–3 layer in the box and on top of that I will keep the mangoes now everybody would happily take this parcel and I will ask the receiver to go and collect it at the station itself to avoid any issue. hence if you noticed here both receiver and sender did some extra work to get that information which is known by none except sender and receiver this extra work is termed as a customized layer,

Code Example: before the code example let’s discuss 2 methods that are required for customization,

1. private void writeObject(ObjectOutputStream oos) throws Exception

This method will be executed automatically at the time of serialization so while doing serialization we have to write the extra code in this method

2. private void readObject(ObjectInputStream ois) throws Exception

This method will be executed automatically at the time of Deserialization so while doing Deserialization we have to write the extra code in this method

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 SerializeDeserializeExample implements Serializable {
String userName = "tanveer";
transient String password = "customized"; // this won't be part of serialization

//we don't have to call it explicitly it will be called automatically by JVM
private void writeObject(ObjectOutputStream oos) throws Exception {
oos.defaultWriteObject();
String change = "key_M" + password;
oos.writeObject(change);
}

//we don't have to call it explicitly it will be called automatically by JVM
private void readObject(ObjectInputStream ois) throws Exception {
ois.defaultReadObject();
String change = (String) ois.readObject();
password = change.substring(5);
}

}

public class main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
SerializeDeserializeExample serializeDeserializeExample = new SerializeDeserializeExample();
//process of serialization
FileOutputStream fos = new FileOutputStream("objGraph.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(serializeDeserializeExample);

//process of Deserialization
FileInputStream fis = new FileInputStream("objGraph.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
SerializeDeserializeExample deserializeExample = (SerializeDeserializeExample) ois.readObject();
System.out.println(deserializeExample.userName + "\n" + deserializeExample.password);
/*
200
*/

}
}

5. Serialization With Respect to Inheritance

..will complete soon rest

References :

Durgasoft Tutorials

--

--

Tanveer
Tanveer

Written by Tanveer

Java software Engineer | Spring (boot, cloud,MVC, webflux) | microservices | docker, kubernetes | Kafka, Elk | AWS |

No responses yet