View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Understanding the Serializable in Java: Serializable Interface with Examples

By Sriram

Updated on May 28, 2025 | 18 min read | 15.04K+ views

Share:

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.

What is Serialization & Deserialization in Java? Definition & Difference

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.

Methods of Making a Class Serializable 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.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Ready to learn programming? Start with Core Java Basics, a free beginner-friendly course from upGrad. Build a strong Java foundation, gain hands-on experience, and master key concepts for software development. Perfect for new coders or those sharpening their skills—join now and get started.

What is the Serializable Interface in Java?

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. 

Serializable Interface in Java: Step-by-Step Process

Let’s break down each step involved in making a class serializable in Java, saving an object’s state, and restoring it later.

Step 1: Create a Serializable Class

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:

  • The class Book implements Serializable, so Java knows it can safely serialize instances of this class.
  • The class has three fields: title, author, and year.
  • No additional methods are required to implement the interface — it’s a marker.

Why this matters:

If the class did not implement Serializable in Java, attempting to serialize an instance would throw a NotSerializableException.

Step 2: Serialize the Object

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:

  • A Book object is created with sample data.
  • FileOutputStream opens (or creates) a file named book.ser where the serialized data will be saved.
  • ObjectOutputStream wraps the file stream and handles converting the object into bytes.
  • writeObject(book) performs the serialization.
  • Streams are closed properly to avoid resource leaks.
  • The message “Book object serialized” confirms the process was successful.

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.

Step 3: Deserialize the Object

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:

  • The program opens the same book.ser file for reading.
  • ObjectInputStream reads the bytes and reconstructs the Book object.
  • The readObject() method returns an Object, so it’s cast back to Book.
  • The fields title, author, and year contain the exact data that was serialized.
  • Streams are closed properly.
  • The final print statement displays the restored data.

Expected Output: 
Deserialized Book: Java Fundamentals, John Smith, 2022

Why this output matters:

  • It confirms that the object was successfully serialized and deserialized without losing any data. The Book object’s state has been fully preserved across the storage and retrieval process.
  • Proper handling of streams and exceptions is key to smooth serialization and deserialization. Streams move the object data to and from storage or computer networks, so managing them correctly prevents errors and resource leaks. Catching exceptions like IOException ensures your program handles problems like missing files or incompatible classes gracefully.
  • Serialization in Java is useful for caching, networking, and session storage. But since it's not cross-language compatible, developers often use formats like JSON or Protocol Buffers for broader interoperability.

Kickstart your coding journey with upGrad’s JavaScript Basics Course. Get hands-on experience with core JavaScript concepts and start building interactive websites today. No prior experience needed—just a willingness to learn. Join now and unlock new opportunities in tech!

Next up is a zoomed look into the advantages and disadvantages of using serialization in Java.

Advantages & Challenges of Using a Serializable Interface 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. 

  • Always declare a serialVersionUID in your class to maintain version control and prevent unexpected exceptions during deserialization.
  • Use the transient keyword to avoid serializing sensitive data like passwords or tokens.
  • Keep the object graph as simple as possible to reduce serialization overhead.
  • Consider alternative methods for critical systems where security and performance are top priorities.

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. 

Serial Version UID in Java

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

  • Change it for breaking changes: If you modify the class in a way that changes its structure (e.g., removing fields, changing types), update the serialVersionUID to indicate an incompatible change.
  • Keep it the same for safe changes: If you add new fields or make compatible changes, maintain the same serialVersionUID to preserve backward compatibility.

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. 

Exploring the Transient Keyword in Java Serialization

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?

  • Protect sensitive information: Fields like passwords, security tokens, or encryption keys should never be serialized to avoid exposing them when data is saved or sent over a network.
  • Avoid saving temporary or derived data: Sometimes, objects contain fields calculated at runtime or relevant only during a session. Marking these as transient in Java prevents unnecessary serialization.
  • Prevent serialization errors: Some fields may refer to objects that are not serializable or are context-specific (e.g., open database connections). Marking these as transient avoids serialization failures.

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:

  • The username field will be saved as usual.
  • The password field will not be included in the serialized data because it is marked as transient.

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. 

Customizing Serialization (readObject and writeObject Methods)

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. 

  • Handle transient or sensitive fields: Transient fields are skipped by default. You might want to serialize them in a controlled way (e.g., encrypting sensitive data).
  • Data transformation: You may want to modify the data during serialization, such as compressing, encrypting, or altering values to save space or protect privacy.
  • Backward compatibility: Customize how data is read from older versions or handle missing/new fields gracefully.
  • Add extra data: Sometimes, you want to serialize additional information that is not present as fields in the object.

How It Works

  • Inside writeObject(), you can call defaultWriteObject() to perform default serialization of non-transient fields, then add extra data using methods like writeInt()writeObject(), etc.
  • Inside readObject(), call defaultReadObject() to restore default fields, then read the extra data in the same order you wrote it.

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.

  • In writeObject(), after the default serialization of name, the code manually writes age * 2 to the stream.
  • In readObject(), it reads that the integer back and divides by 2 to restore the original age value.

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

Enhance Your Java Skills with upGrad!

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

Frequently Asked Questions (FAQs)

1. What happens if a class does not implement the Serializable interface in Java, but serialization is attempted?

2. Can static fields be serialized in Java?

3. How can I exclude specific fields from the serialization without using the transient keyword?

4. Is it possible to serialize an object with circular references in Java?

5. What is the default behavior if serialVersionUID is not explicitly declared?

6. Can you serialize objects that contain references to non-serializable classes?

7. How does serialization affect application performance?

8. Can serialization be used to communicate between different programming languages?

9. How do I handle versioning when deserializing objects from older versions of a class?

10. Is it possible to encrypt serialized data for security?

11. How can I test if my class is correctly implementing serialization?

Sriram

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

+91

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

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months