Serialization and Deserialization in Java Part: 1
In this blog, I will explain what Serialization and Deserialization are in Java. Furthermore, I show how we can use it practically.
Serialization: — Serialization is the process of writing an object’s states to a file, but it is more precisely the process of converting an object from a Java-supported form to either a file-supported form or a network-supported form. Serialization can be implemented using the FileOutputStream or ObjectOutputStream classes.
Deserialization: — Deserialization refers to the process of reading an object’s states from a file, but it is more accurately defined as the process of converting an object from a file-supported or network-supported form into a Java-supported form. Deserialization can be implemented using the FileInputStream or ObjectInputStream classes.
I’ve added a code snippet for object serialization and deserialization here.
package org.example;
import java.io.*;
class Employee implements Serializable {
int empId = 1456;
String department = "development";
}
public class SerializationDemo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Employee employee = new Employee();
//Process of serializing of an object
FileOutputStream fileOutputStream = new FileOutputStream("employee.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(employee);
//Process of deserializing of an object
FileInputStream fileInputStream = new FileInputStream("employee.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Employee existingEmployee = (Employee) objectInputStream.readObject();
System.out.println("Employee Id: " + existingEmployee.empId + "\nEmployee Department: " + existingEmployee.department);
}
}
/**
* Employee Id: 1456
* Employee Department: development
**/
Only serializable objects can be serialized; an object is said to be serializable if and only if the corresponding class implements the Serializable interface. The Serializable interface is present in the java.io package, but it lacks methods. As a result, it’s a marker interface.
If we try to serialize a non-serializable object, we will receive a runtime exception that says NotSerializableException.
To summarise, if we want to save or persist the states of an object while transmitting it over networks or in files, we must implement a serializable interface; otherwise, we will receive a NotSerializableException.
In the next blog, I’ll explain how to prevent sensitive data during serialization and deserialization.