Understanding the Serializable in Java: Serializable Interface with Examples
By Sriram
Updated on May 28, 2025 | 18 min read | 15.04K+ views
Share:
For working professionals
For fresh graduates
More
By Sriram
Updated on May 28, 2025 | 18 min read | 15.04K+ views
Share:
Table of Contents
Did you know? The earliest form of serialization was shaped by the Xerox Network Systems Courier technology in the early 1980s. It wasn't until the late 1990s that a text-based encoding system, readable by humans, was introduced. |
The serializable interface in Java is essential for converting objects into a byte stream, allowing their state to be saved to a file or sent over a network. By implementing this simple marker interface, a class indicates that its objects can be serialized, which is crucial for persisting data or transferring it between systems.
While formats like JSON and XML can be used for data exchange, they don't preserve the full object state like Java serialization does. These formats focus on data representation, not the complete object structure or behavior, making them unsuitable for scenarios requiring full object persistence. Without serialization, Java objects can't be easily stored or transferred in their entirety.
This blog explains that in Java what is serializable interface, covers serialization/deserialization examples, challenges, and customizing serialization for complex use cases in Java.
Ready to specialize in Cyber Security, Full Stack Development, Game Development, and more? upGrad’s Software Engineering course part of the updated Generative AI curriculum, prepares you for leadership roles such as Development Manager or CTO, while mastering key programming languages and practical projects.
Java objects can’t be stored or transmitted directly due to JVM-managed memory, which keeps them in a format specific to the Java Virtual Machine. Serialization bridges this gap by converting an object’s state into a sequence of bytes, making it platform-independent and enabling easy storage or transmission across systems. This byte stream represents the object’s data and data structure in a format that can be easily stored in a file, shared over a network, or saved in a database.
Example: When a user’s session data needs to be saved for restoration after a server restart, serialization converts the session object into a byte stream, which can later be read to reconstruct the session.
Deserialization is the opposite of serialization. It takes the byte stream and reconstructs the original Java object in memory, allowing the program to retrieve and work with the saved state. This allows the program to retrieve the saved state and work with it as if it were the original object.
Want to excel in programming and build a strong foundation for your tech career? Explore upGrad’s range of courses designed to sharpen your skills and boost your confidence:
Here’s an example of serialization and deserialization in Java for sharing student data.
Example of Serialization:
import java.io.*;
class Student implements Serializable {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
public class SerializationExample {
public static void main(String[] args) throws IOException {
Student student = new Student("Raj", 21);
FileOutputStream fileOut = new FileOutputStream("student.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(student);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in student.ser");
}
}
Output:
Serialized data is saved in student.ser
Output Explanation:
The ObjectOutputStream serializes the Student object by converting its state into a byte stream and saving it to student.ser. This process stores the object’s data in a platform-independent format, ensuring its state is preserved even after the object is removed from memory.
Example of Deserialization:
import java.io.*;
class Student implements Serializable {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
public class DeserializationExample {
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileInputStream fileIn = new FileInputStream("student.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Student student = (Student) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized Student: " + student.name + ", " + student.age);
}
}
Output:
Deserialized Student: Raj, 21
Output Explanation:
This output shows that the program has read the byte stream from the student.ser file and reconstructed it back into a Student object in memory. The fields name and age retain their original values, "Raj" and 21, confirming that the object’s state was preserved correctly during the serialization and deserialization process.
In short, serialization is used when you need to persist or transfer objects, while deserialization is used to restore them.
Also Read: Java Tutorial: Learn Java Programming From Scratch For Beginners
Now, let’s move ahead and take a look at the making of a Serialization Interface in Java.
To make an object serializable in Java, its class must implement the Serializable interface from the java.io package. This marker interface has no methods but signals to the JVM that objects of the class can be converted to a byte stream for storage or transfer. It prevents unintended serialization, offering better control over performance and security.
By marking a class with Serializable, you are telling Java’s serialization mechanism: “It’s safe to convert instances of this class into a byte stream and later reconstruct them.” Without this, attempting to serialize an object will throw a NotSerializableException.
The Serializable interface in Java is a marker interface used to enable serialization. It is a flag interface that contains no methods but indicates to the Java Virtual Machine (JVM) that the class is capable of being serialized. When a class implements Serializable in Java, it allows the program’s built-in serialization mechanism to process its objects, converting them to bytes and vice versa.
import java.io.*;
class Employee implements Serializable {
int empId;
String name;
Employee(int empId, String name) {
this.empId = empId;
this.name = name;
}
}
public class EmployeeSerializationExample {
public static void main(String[] args) throws IOException {
// Imagine this employee works at an IT company in Bengaluru
Employee emp = new Employee(101, "Amit Sharma");
// Serialize the employee object and save it in a file named employee.ser
FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(emp);
out.close();
fileOut.close();
System.out.println("Serialized employee data saved");
}
}
Explanation:
In this example, we create an Employee object representing Amit Sharma, an employee at an IT firm. By implementing the Serializable interface in Java, we enable Amit’s employee details, like employee ID and name, to be converted into a byte stream. This byte stream is then saved in a file called employee.ser.
This method could be useful in a scenario where an HR system in Mumbai needs to temporarily save employee records or send employee information securely across branches in Delhi, Hyderabad, or Pune. Serialization ensures that Amit’s data can be transferred or stored efficiently and later restored back into a Java object whenever needed.
Also Read: Exploring Java Architecture: A Guide to Java's Core, JVM and JDK Architecture
Now that you know that in Java what is serializable interface, let’s look at its implementation.
Let’s break down each step involved in making a class serializable in Java, saving an object’s state, and restoring it later.
Before you can serialize an object, its class must implement the Serializable interface in Java. The marker interface tells Java that objects in this class can be converted into a byte stream.
import java.io.Serializable;
class Book implements Serializable {
String title;
String author;
int year;
Book(String title, String author, int year) {
this.title = title;
this.author = author;
this.year = year;
}
}
Explanation:
Why this matters:
If the class did not implement Serializable in Java, attempting to serialize an instance would throw a NotSerializableException.
Now, create an instance of the Book class and write it to a file using ObjectOutputStream. This converts the object into a byte stream and saves it.
import java.io.*;
public class SerializationStepByStep {
public static void main(String[] args) throws IOException {
Book book = new Book("Java Fundamentals", "John Smith", 2022);
FileOutputStream fileOut = new FileOutputStream("book.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(book); // Serialization happens here
out.close();
fileOut.close();
System.out.println("Book object serialized");
}
}
Explanation:
What happens behind the scenes:
The Book object is flattened into bytes that capture its field values and class information. This byte stream is written into book.ser.
To restore the Book object from the file, you read the byte stream and convert it back into an object using ObjectInputStream.
import java.io.*;
public class DeserializationStepByStep {
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileInputStream fileIn = new FileInputStream("book.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Book book = (Book) in.readObject(); // Deserialization happens here
in.close();
fileIn.close();
System.out.println("Deserialized Book: " + book.title + ", " + book.author + ", " + book.year);
}
}
Explanation:
Expected Output:
Deserialized Book: Java Fundamentals, John Smith, 2022
Why this output matters:
Next up is a zoomed look into the advantages and disadvantages of using serialization in Java.
Serialization in Java offers a powerful way to persist and transfer object states. However, like any technology, it comes with its own set of benefits and pitfalls, such as handling complex object graphs, class versioning, and potential breaking changes across versions.
Aspect |
Advantages |
Challenges |
Persistence | Easily save and restore object states, ideal for session management and caching. | Changes to class fields or structure can cause deserialization failures. |
Data Transfer | Simplifies sending objects between Java applications across networks. | Large or nested objects can slow performance and increase memory usage. |
Ease of Use | Simple marker interface enables easy integration with Java I/O classes. | Requires managing serialVersionUID for version compatibility. |
Data Security | Exclude sensitive data using the transient keyword to prevent unwanted serialization. | Serialized data can be intercepted; use encryption or SSL/TLS for protection. |
Flexibility | Supports complex object graphs, serializing entire hierarchies. | All related objects must be serializable, which complicates the design. |
Best Practices for Using Serializable Interface
Here are some tips to ensure that your serializable interface in Java functions properly without any security risks or other issues.
Serialization in Java is powerful but comes with its challenges. To master this and other advanced development skills, check out the Generative AI Mastery Certificate for Software Development from upGrad. Gain expertise in AI and software development with hands-on experience. Enroll now and take the next step in your career!
Also Read: What is End-to-End Encryption? How It Works, and Why We Need It
Now you know what’s best for your serializable interface in Java, let’s understand serial Version UID in little more detail.
A key part of Java serialization interface is the Serial Version UID (serialVersionUID), a unique identifier assigned to each serializable class. It acts like a version control number that ensures the serialized object matches the class definition during deserialization.
How serialVersionUID Works
When an object is serialized, its class’s serialVersionUID is embedded in the byte stream. During deserialization, Java compares the UID in the byte stream with the one in the current class version. If they don't match, Java throws an InvalidClassException, indicating an incompatible change in the class structure.
When to Change serialVersionUID
Tip: Change serialVersionUID only for breaking changes. Keep it the same for safe field additions.
Explicitly managing serialVersionUID is essential for maintaining stable serialization contracts, especially in long-term projects, distributed systems, or when serialized data needs to persist across different application versions.
Also Read: Types of Variables in Java: Java Variables Explained
How to Define Serial Version UID
If you don’t define it, Java automatically generates one based on the class’s structure, but this can lead to unpredictable mismatches. To avoid this, declare a serialVersionUID as a static final long value in your class:
private static final long serialVersionUID = 1L;
Each time you make a significant, incompatible change to the class, you can update this number to indicate that older serialized objects may no longer be compatible.
Example:
import java.io.Serializable;
class Employee implements Serializable {
private static final long serialVersionUID = 1L;
int empId;
String name;
Employee(int empId, String name) {
this.empId = empId;
this.name = name;
}
}
Explanation:
Here, the serialVersionUID is explicitly set to 1L. If the class changes later in a way that affects serialization, you can increment this ID to signal incompatibility.
Besides the serial version UID, you also have to understand transient keywords in Java to protect sensitive information.
When you serialize an object in Java, all of its non-static and non-transient fields are converted into a byte stream and saved or transmitted. However, there are cases where you might want to exclude certain fields from this process, especially when those fields contain sensitive or temporary data that should not be persisted or shared. This is where the transient keyword comes into play.
The transient keyword tells the Java serialization mechanism to skip the marked field when converting the object into a byte stream. This means the field’s value will not be saved during serialization, and upon deserialization, it will be initialized with the default value for its type (e.g., null for objects, 0 for integers).
Looking to deepen your programming knowledge? Start with Advanced JavaScript, a free course from upGrad. Learn advanced concepts and techniques that will help you strengthen your JavaScript skills and tackle more complex projects. Join now to build your expertise with practical lessons and real-world applications!
Why Use the Transient Keyword when making an object serializable in Java?
Example:
import java.io.Serializable;
class User implements Serializable {
String username;
transient String password; // This field will not be serialized
User(String username, String password) {
this.username = username;
this.password = password;
}
}
In this example, when a User object is serialized:
When the object is deserialized, password will be set to null (the default for String in Java), so sensitive information like the password is protected and not exposed accidentally.
Also Read: Data Governance vs Data Security: Key Differences, Tools & Real-World Use Cases
Meanwhile, you can also customize the process of making your object serializable in Java.
By default, a serializable interface in Java is processed automatically for any class that implements Serializable in Java. It serializes all non-transient fields by converting the entire object graph into a byte stream, and later reconstructs it during deserialization. However, there are cases where this default behavior isn’t enough, and you might want to control exactly how some fields are saved or restored. This is where custom serialization comes into play.
Java allows you to customize the serialization process by defining two special methods in your class:
private void writeObject(ObjectOutputStream oos)
private void readObject(ObjectInputStream ois)
These methods let you add your own logic for writing to and reading from the stream, supplementing or overriding the default behavior.
Why Customize Serialization in Java?
Here are a few reasons why you might want to customize your serializable interface in Java.
How It Works
Example:
import java.io.*;
class Person implements Serializable {
String name;
transient int age; // This field is transient, so skipped by default
Person(String name, int age) {
this.name = name;
this.age = age;
}
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject(); // Serialize non-transient fields (name)
oos.writeInt(age * 2); // Custom serialization: store age multiplied by 2
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject(); // Deserialize non-transient fields (name)
age = ois.readInt() / 2; // Custom deserialization: divide stored value by 2 to get original age
}
}
Explanation:
The age field is marked transient, so it wouldn’t normally be serialized.
This demonstrates how you can include transient fields in serialization, with some transformation logic.
Custom serialization lets you control how objects are converted to byte streams, helping protect sensitive data, maintain class compatibility, and improve performance. But it can make code fragile if fields or logic change—use with care in evolving systems.
Also Read: What is Composition in Java With Examples
Serialization is vital for storing and transferring data in Java applications, but it comes with challenges like versioning, compatibility, and security. To avoid issues, update serialVersionUID only for breaking changes, use transient for sensitive fields, and secure data with encryption or SSL/TLS during transmission.
If you want to confidently navigate these issues and write Java programs that manage object persistence and data transfer reliably, upGrad is here to help build strong skills in programming language. Here are some courses to choose from:
Feeling unsure about which skills to focus on or which course fits your goals best? Connect with upGrad’s expert counsellors or visit our offline centres—they’re here to listen, guide, and help you choose the path that suits you.
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
Reference:
https://en.wikipedia.org/wiki/Serialization
182 articles published
Meet Sriram, an SEO executive and blog content marketing whiz. He has a knack for crafting compelling content that not only engages readers but also boosts website traffic and conversions. When he'sno...
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources