Introduction
In Java, objects exist in memory only while a program is running. Once the program terminates, all objects stored in memory are lost unless they are saved somewhere permanently. This is where Serialization becomes important.
Serialization is the process of converting a Java object into a stream of bytes so that it can be stored in a file, sent over a network, or transferred between different systems. Later, the byte stream can be converted back into the original object using a process called Deserialization.
Java provides built-in support for serialization through the java.io package. To make an object serializable, the class must implement the Serializable interface.
What is Java Serialization?
Serialization is the process of converting a Java object into a sequence of bytes.
The generated byte stream can be:
- Stored in a file
- Saved in a database
- Sent across a network
- Transmitted between applications
- Used for caching
Later, the object can be reconstructed through deserialization.
Why Do We Need Serialization?
Serialization is useful in many real-world scenarios.
Common use cases include:
- Saving objects to files
- Sending objects over a network
- Web session management
- Distributed applications
- Remote Method Invocation (RMI)
- Object caching
- Message queues
- Data backup
Without serialization, Java objects cannot be easily transferred outside the JVM.
How Serialization Works?
Serialization follows these steps:
- Create an object.
- Make the class implement Serializable.
- Use ObjectOutputStream.
- Write the object to a file or output stream.
- Convert the object into bytes.
To restore the object:
- Read the byte stream.
- Use ObjectInputStream.
- Convert bytes back into an object.
Serializable Interface
The Serializable interface is a marker interface.
Package:
import java.io.Serializable;
It contains no methods.
Its purpose is to inform the JVM that objects of the class are allowed to be serialized.
Example:
import java.io.Serializable;
public class Student implements Serializable {
private int id;
private String name;
}
Serializing an Object
The ObjectOutputStream class writes objects to an output stream.
Example
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.IOException;
class Student implements Serializable {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student(101, "Rahul");
try {
FileOutputStream file =
new FileOutputStream("student.ser");
ObjectOutputStream output =
new ObjectOutputStream(file);
output.writeObject(student);
output.close();
System.out.println("Object serialized successfully.");
} catch(IOException e) {
e.printStackTrace();
}
}
}
Output
A file named student.ser is created containing the serialized object.
Deserialization Overview
Deserialization is the reverse process of serialization.
It converts the byte stream back into an object.
Example:
FileInputStream file =
new FileInputStream("student.ser");
ObjectInputStream input =
new ObjectInputStream(file);
Student student =
(Student) input.readObject();
This restores the original object from the serialized file.
What is serialVersionUID?
serialVersionUID is a unique version identifier for a serializable class.
Example:
private static final long serialVersionUID = 1L;
It helps verify that the sender and receiver of a serialized object have compatible class definitions.
If the class changes and the serialVersionUID does not match, Java throws an InvalidClassException.
Why Use serialVersionUID?
It provides:
- Version control
- Class compatibility
- Safe deserialization
- Better maintainability
Always declare serialVersionUID explicitly in serializable classes.
The transient Keyword
Sometimes certain fields should not be serialized.
Use the transient keyword.
Example:
class Employee implements Serializable {
String name;
transient String password;
}
Here:
- name is serialized.
- password is ignored.
This is useful for protecting sensitive information.
Static Variables and Serialization
Static variables belong to the class rather than individual objects.
Therefore, static fields are not serialized.
Example:
class Company implements Serializable {
static String companyName = "ABC Ltd.";
String employee;
}
Only employee is serialized.
Serialization Process Flow
Java Object
│
▼
ObjectOutputStream
│
▼
Byte Stream
│
▼
File / Network / Database
│
▼
ObjectInputStream
│
▼
Original Java Object
Real-Life Example
Suppose an online banking application stores user session information.
class UserSession implements Serializable {
private static final long serialVersionUID = 1L;
String username;
long loginTime;
}
The application serializes the session object and stores it temporarily.
Later, it deserializes the object to restore the user’s session.
Advantages of Serialization
- Saves object state
- Supports object transfer over networks
- Useful for caching
- Enables persistent storage
- Easy to implement
- Built into Java
- Widely supported across Java frameworks
Limitations of Serialization
- Slower than some modern serialization libraries
- Serialized files are not human-readable
- Sensitive data may be exposed if not handled carefully
- Class changes can cause compatibility issues
- Increases application size for large object graphs
Common Mistakes
1. Forgetting to Implement Serializable
Incorrect:
class Student {
}
Correct:
class Student implements Serializable {
}
Otherwise, Java throws a NotSerializableException.
2. Not Declaring serialVersionUID
Incorrect:
class Student implements Serializable {
}
Correct:
private static final long serialVersionUID = 1L;
Explicitly declaring it helps maintain compatibility across versions.
3. Serializing Sensitive Information
Incorrect:
String password;
Correct:
transient String password;
Sensitive fields such as passwords, tokens, and temporary session data should generally not be serialized.
4. Forgetting to Close Streams
Incorrect:
ObjectOutputStream output =
new ObjectOutputStream(file);
Correct:
output.close();
Or use try-with-resources.
Best Practices
- Always declare serialVersionUID.
- Serialize only objects that need persistence or transfer.
- Mark confidential fields as transient.
- Use try-with-resources for stream handling.
- Validate deserialized data before using it.
- Keep serialized object graphs as small as practical.
- Prefer modern serialization frameworks (such as JSON or Protocol Buffers) when interoperability with non-Java systems is required.
Serialization vs Deserialization
| Serialization | Deserialization |
|---|---|
| Converts an object into bytes | Converts bytes into an object |
| Uses ObjectOutputStream | Uses ObjectInputStream |
| Saves data | Restores data |
| Writes to a file or network | Reads from a file or network |
Serialization vs Externalization
| Serialization | Externalization |
|---|---|
| Automatic | Manual |
| Uses Serializable | Uses Externalizable |
| Easier to implement | Gives more control |
| Serializes all eligible fields | Programmer decides what to serialize |
Conclusion
Java Serialization is a powerful feature that allows objects to be converted into byte streams for storage or transmission. It plays a significant role in distributed systems, caching, session management, file storage, and remote communication. By implementing the Serializable interface, using ObjectOutputStream and ObjectInputStream, declaring a proper serialVersionUID, and marking sensitive fields as transient, developers can safely and efficiently preserve object state.