Introduction
In Java, objects created during program execution exist only in memory. If you want to restore an object that was previously saved to a file, database, or transmitted over a network, Java provides a mechanism called Deserialization.
Deserialization is the process of converting a stream of bytes back into its original Java object. It is the reverse operation of Serialization, where an object is converted into a byte stream. Together, serialization and deserialization enable Java applications to persist object state, exchange objects across networks, cache data, and maintain user sessions.
Java provides built-in support for deserialization through the java.io package using the ObjectInputStream class. During deserialization, Java reconstructs the object in memory using the serialized byte stream.
What is Java Deserialization?
Deserialization is the process of converting a serialized byte stream back into its original Java object.
When an object is serialized, it is stored as a sequence of bytes. During deserialization, Java reads those bytes and reconstructs the object with its original state.
Deserialization allows applications to:
- Restore saved objects
- Load application settings
- Recover user sessions
- Read cached objects
- Receive objects over a network
- Process stored application data
Why Do We Need Deserialization?
Deserialization is useful in many real-world applications.
Common use cases include:
- Loading saved objects from files
- Restoring user sessions
- Reading cached data
- Receiving serialized objects from a network
- Distributed applications
- Remote Method Invocation (RMI)
- Backup and recovery systems
- Persistent object storage
Without deserialization, serialized objects cannot be restored into usable Java objects.
How Deserialization Works?
The deserialization process follows these steps:
- Open the serialized file or input stream.
- Create an ObjectInputStream.
- Read the object using the readObject() method.
- Cast the returned object to its original class.
- Use the restored object in the application.
The object retains the values it had at the time it was serialized.
Prerequisite: Serializable Class
Only objects whose classes implement the Serializable interface can be deserialized.
Example:
import java.io.Serializable;
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
}
The Serializable interface is a marker interface and does not declare any methods.
Deserializing an Object
The ObjectInputStream class is used to read serialized objects.
Example
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileInputStream file =
new FileInputStream("student.ser");
ObjectInputStream input =
new ObjectInputStream(file);
Student student =
(Student) input.readObject();
input.close();
System.out.println(student.id);
System.out.println(student.name);
} catch(IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output
Rahul
The object is restored with the same values it had when it was serialized.
How readObject() Works?
The readObject() method reads the next serialized object from the input stream.
Syntax:
Object object = input.readObject();
Since it returns an Object, you must cast it to the appropriate class.
Example:
Student student =
(Student) input.readObject();
Using try-with-resources
The recommended approach is to use try-with-resources.
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (ObjectInputStream input =
new ObjectInputStream(
new FileInputStream("student.ser"))) {
Student student =
(Student) input.readObject();
System.out.println(student.name);
} catch(IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
This automatically closes the stream after use.
What is serialVersionUID?
serialVersionUID is a unique identifier for a serializable class.
Example:
private static final long serialVersionUID = 1L;
During deserialization, Java checks whether the serialVersionUID stored in the serialized object matches the current class definition.
If they differ, Java throws an InvalidClassException.
Effect of transient Fields
Fields marked with the transient keyword are not serialized.
Example:
class Employee implements Serializable {
String name;
transient String password;
}
After deserialization:
name = Rahul
password = null
Since password was never serialized, it is restored with its default value.
Static Variables and Deserialization
Static variables are not part of an object’s serialized state.
Example:
class Company implements Serializable {
static String companyName = "ABC Ltd.";
String employee;
}
After deserialization:
- employee is restored from the serialized data.
- companyName uses the current value from the class, not the serialized object.
Deserialization Process Flow
Serialized Object (.ser File)
│
▼
FileInputStream
│
▼
ObjectInputStream
│
▼
readObject()
│
▼
Original Java Object
Exceptions in Deserialization
Several exceptions may occur.
| Exception | Description |
|---|---|
| IOException | General input/output error |
| ClassNotFoundException | Serialized class cannot be found |
| InvalidClassException | serialVersionUID mismatch |
| OptionalDataException | Primitive data encountered unexpectedly |
| StreamCorruptedException | Corrupted serialization stream |
Always handle these exceptions properly.
Real-Life Example
Suppose an online shopping application stores the customer’s cart when the user logs out.
class ShoppingCart implements Serializable {
private static final long serialVersionUID = 1L;
String customerName;
int totalItems;
}
When the customer logs in again, the application deserializes the cart.
ShoppingCart cart =
(ShoppingCart) input.readObject();
The shopping cart is restored exactly as it was saved.
Advantages of Deserialization
- Restores object state
- Supports persistent storage
- Enables object transfer across networks
- Simplifies session recovery
- Useful in distributed applications
- Built into Java
- Easy to implement
Limitations of Deserialization
- Only works with serializable classes
- Can cause compatibility issues if class definitions change
- Serialized data is not human-readable
- Can introduce security risks when reading untrusted data
- Requires careful exception handling
Common Mistakes
1. Forgetting to Implement Serializable
Incorrect:
class Student {
}
Correct:
class Student implements Serializable {
}
Otherwise, serialization and deserialization will fail.
2. Ignoring serialVersionUID
Incorrect:
class Student implements Serializable {
}
Correct:
private static final long serialVersionUID = 1L;
Declaring it explicitly helps maintain compatibility across versions.
3. Forgetting to Cast readObject()
Incorrect:
Object obj = input.readObject();
Correct:
Student student =
(Student) input.readObject();
readObject() always returns an Object.
4. Deserializing Untrusted Data
Never deserialize data from unknown or untrusted sources without validation. Malicious serialized objects can pose security risks.
5. Forgetting to Close Streams
Incorrect:
ObjectInputStream input =
new ObjectInputStream(file);
Correct:
input.close();
Or use try-with-resources.
Best Practices
- Always implement Serializable for classes that need deserialization.
- Declare serialVersionUID explicitly.
- Use try-with-resources.
- Handle both IOException and ClassNotFoundException.
- Avoid deserializing data from untrusted sources.
- Mark confidential fields as transient.
- Keep serialized classes backward compatible whenever possible.
Serialization vs Deserialization
| Serialization | Deserialization |
|---|---|
| Converts objects into bytes | Converts bytes into objects |
| Uses ObjectOutputStream | Uses ObjectInputStream |
| Saves object state | Restores object state |
| Writes data | Reads data |
Conclusion
Java Deserialization is the process of reconstructing Java objects from a serialized byte stream. It enables applications to restore saved object state, recover user sessions, load cached data, and exchange objects across networks. Using ObjectInputStream together with classes that implement the Serializable interface makes deserialization straightforward and powerful.