Lesson 57
Serialization and Deserialization
Serialization converts a Java object into a byte stream for storage or transmission, while deserialization reverses the process to reconstruct the object. Java provides the Serializable interface along with ObjectOutputStream and ObjectInputStream to support this.
Java Track
Save progress as you learn.
61 lessons
Lesson content
Serialization in Java is the process of converting an object into a byte stream so it can be stored or transmitted. Deserialization is the reverse process, where the byte stream is converted back into a Java object.
What is Serialization in Java?
Serialization is a mechanism that converts the state of an object into a byte stream. This byte stream can be stored in a file, sent across a network, saved in a database, or transferred between systems. The serialized object can later be reconstructed using deserialization.
Key Terms
- Serialization: The process of converting an object into a byte stream.
- Deserialization: The process of converting a byte stream back into an object.
- Serializable Interface: A marker interface that enables serialization.
- Externalizable Interface: A subinterface of Serializable that allows custom serialization.
- ObjectOutputStream: A class used to serialize objects.
- ObjectInputStream: A class used to deserialize objects.
- Transient Keyword: Prevents a field from being serialized.
Why Do We Need Serialization?
When an object is created, it exists in memory only while the program is running. After the program terminates, the object is destroyed. Serialization helps by saving object state permanently, reusing object data later, sending objects across networks, supporting distributed applications, and making data platform-independent.
Benefits of Serialization
- Object state can be persisted.
- Objects can be transferred between systems.
- Serialized data is platform-independent.
- Supports distributed computing and networking.
How Serialization Works
Serialization Process
Java Object
│
▼
Serialization
│
▼
Byte Stream
│
Stored in File / Sent over NetworkDeserialization Process
Byte Stream
│
▼
Deserialization
│
▼
Java ObjectSerializable Interface
To serialize an object, the class must implement the java.io.Serializable interface. The Serializable interface does not contain any methods. It simply informs the JVM that objects of the class can be serialized.
Syntax
import java.io.Serializable;
public class Employee implements Serializable {
}Example 01: Java Serialization
This example demonstrates how to serialize an Employee object into a file.
package com.java.Serializing_deserializing;
import java.io.*; //importing the package
public class Serialization_class {
public static void main(String[] args) {
Employee emp = new Employee(); //creating an object for the emp class
emp.name = "Kishore ragav"; //assigning values using the instance created
emp.address = "Chengalpet";
emp.age = 21;
emp.salary = 22000;
try {
FileOutputStream fout = new FileOutputStream("F:\\Serialization.txt"); //creating a file
ObjectOutputStream objout = new ObjectOutputStream(fout); //converting the instance into stream of bytes
objout.writeObject(emp);
objout.close();
fout.close();
System.out.println("class has been serialized successfully");
} catch (IOException e) {
e.printStackTrace();
}
}
}How It Works
- Step 1: Create an Employee object.
- Step 2: Assign values to its fields.
- Step 3: Create a FileOutputStream.
- Step 4: Create an ObjectOutputStream.
- Step 5: Use objout.writeObject(emp); to serialize the object.
ObjectOutputStream Class
The ObjectOutputStream class is used to serialize Java objects.
Method
public final void writeObject(Object obj)
throws IOExceptionPurpose: Converts an object into a byte stream and writes it to a file or output stream.
Example 02: Java Deserialization
This example demonstrates how to restore a serialized object.
package com.java.Serializing_deserializing;
/* as we have serialized a method in order retrieve it to its object form we need to deserialize it*/
import java.io.*; //importing the package
public class Deserializing_class {
public static void main(String[] args) throws IOException, ClassNotFoundException { //throwing the exception that may be caused
Employee emp = null;
try {
FileInputStream filein = new FileInputStream("F:\\Serialization.txt");
ObjectInputStream objin = new ObjectInputStream(filein);
emp = (Employee) objin.readObject();
objin.close();
filein.close();
}
finally {
System.out.println("Deserializing the class");
System.out.println("The name of the Employee is " +emp.name);
System.out.println("The age of the employee is "+emp.age);
System.out.println("The address of the employee is "+emp.address);
System.out.println("The salary of the employee is "+emp.salary);
}
}
}How It Works
- Step 1: Open the serialized file.
- Step 2: Create an ObjectInputStream.
- Step 3: Read the object using emp = (Employee) objin.readObject();
- Step 4: Convert the byte stream back into an Employee object.
- Step 5: Display the object's data.
ObjectInputStream Class
The ObjectInputStream class is used to deserialize objects.
Method
public final Object readObject()
throws IOException,
ClassNotFoundExceptionPurpose: Reads serialized object data and recreates the original object.
Example 03: Customized Serialization
Java allows customized serialization using the writeObject() and readObject() methods.
package com.java.Serializing_deserializing;
//Java program to illustrate customized serialization
import java.io.*;
class Custom implements Serializable {
String username = "lw_java";
transient String pwd = "java";
// Performing customized serialization using the below two methods:
// this method is executed by jvm when writeObject() on
// Account object reference in main method is
// executed by jvm.
private void writeObject(ObjectOutputStream oos) throws Exception
{
// to perform default serialization of Account object.
oos.defaultWriteObject();
// epwd (encrypted password)
String epwd = "123" + pwd;
// writing encrypted password to the file
oos.writeObject(epwd);
}
// this method is executed by jvm when readObject() on
// Account object reference in main method is executed by jvm.
private void readObject(ObjectInputStream ois) throws Exception
{
// performing default deserialization of Account object
ois.defaultReadObject();
// deserializing the encrypted password from the file
String epwd = (String)ois.readObject();
// decrypting it and saving it to the original password
// string starting from 3rd index till the last index
pwd = epwd.substring(3);
}
}
class ex1{
public static void main(String[] args) throws Exception
{
Custom custom = new Custom();
System.out.println("Username :" + custom.username +
" Password :" + custom.pwd);
FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
// writeObject() method on Account class will
// be automatically called by jvm
oos.writeObject(custom);
FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Custom read_obj = (Custom)ois.readObject();
System.out.println("Username :" + read_obj.username +
" Password :" + read_obj.pwd);
}
}Understanding Transient Fields
The transient keyword prevents a field from being serialized.
transient String pwd = "java";Without custom serialization, the password value would not be saved. Custom serialization allows the password to be encrypted and restored manually.
Advantages of Serialization
- Object Persistence — object state can be saved and restored later.
- Network Communication — objects can be transferred across networks.
- Platform Independence — serialized byte streams can be used on different platforms.
- Easy Data Storage — complex objects can be stored in files.
- Distributed Applications — supports Remote Method Invocation (RMI) and distributed systems.
Important Rules of Serialization
- Rule 1: If a parent class implements Serializable, the child class automatically becomes serializable.
- Rule 2: If a child class implements Serializable, the parent class does not automatically become serializable.
- Rule 3: Only non-static instance variables are serialized.
- Rule 4: Static variables are not serialized.
- Rule 5: Transient variables are not serialized.
- Rule 6: Constructors are not called during deserialization.
- Rule 7: Associated objects must also implement Serializable.
Serializable vs Externalizable
| Feature | Serializable | Externalizable |
|---|---|---|
| Package | java.io | java.io |
| Ease of Use | Easy | More Complex |
| Control | JVM Managed | Developer Managed |
| Methods Required | None | writeExternal(), readExternal() |
| Performance | Standard | Potentially Faster |
Common Exceptions in Serialization
- IOException: Occurs during file operations.
- NotSerializableException: Occurs when a class does not implement Serializable.
- ClassNotFoundException: Occurs during deserialization when the class cannot be found.
- InvalidClassException: Occurs when serialized and current class versions differ.
Best Practices
- Implement Serializable carefully — only serialize objects that need persistence or transfer.
- Use transient for sensitive data — avoid storing passwords and confidential information.
- Close streams properly — always close input and output streams after use.
- Handle exceptions — use try-catch blocks to manage serialization errors.
- Define serialVersionUID — maintain compatibility between different versions of a class.
private static final long serialVersionUID = 1L;FAQ
1. What is serialization in Java?
Serialization is the process of converting a Java object into a byte stream for storage or transmission.
2. What is deserialization in Java?
Deserialization is the process of converting a serialized byte stream back into a Java object.
3. Why is the Serializable interface required?
The Serializable interface informs the JVM that an object can be converted into a byte stream and restored later.
Where Java is used
Java in real-world development
Serializable
Marker interface with no methods that signals to the JVM that a class's objects can be converted to a byte stream.
ObjectOutputStream
Class used to serialize objects via writeObject(), converting them into a byte stream written to a file or stream.
ObjectInputStream
Class used to deserialize objects via readObject(), reconstructing the original object from a byte stream.
transient
Keyword that prevents a field (e.g. a password) from being included in the serialized byte stream.
Externalizable
Subinterface of Serializable requiring writeExternal() and readExternal() for developer-managed, potentially faster serialization.
serialVersionUID
A static final long field that maintains version compatibility between serialized and deserialized class versions.