Java Tutorial 0/145 lessons ~6 min read Lesson 39

    Java Serialization

    java serialization deserialization Serializable serialVersionUID transient ObjectOutputStream ObjectInputStream

    Course progress0%
    Focus
    30 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Learning Objectives

    After completing this lesson, you will be able to:

    • Understand Serialization and Deserialization
    • Learn why Serialization is important
    • Implement the Serializable interface
    • Use ObjectOutputStream and ObjectInputStream
    • Understand serialVersionUID
    • Use the transient keyword
    • Customize Serialization
    • Understand Serialization internals
    • Learn Serialization security risks
    • Compare Java Serialization with JSON
    • Use Serialization in enterprise applications
    • Follow Best Practices
    • Prepare for Java Interview Questions

    Introduction

    Imagine you have an Employee object in memory.

    code
    Employee employee =
    new Employee(
    101,
    "Rahul",
    85000
    );

    When the application stops, this object disappears because it exists only in JVM memory.

    But what if you want to:

    • Save it to a file?
    • Send it over a network?
    • Cache it?
    • Store it in Redis?
    • Transfer it to another JVM?
    • Persist session information?

    Java provides Serialization.

    Serialization converts an object into a sequence of bytes so it can be stored or transmitted.

    Later, those bytes can be converted back into the original object using Deserialization.

    What is Serialization?

    Serialization is the process of converting a Java object into a byte stream.

    code
    Java Object
    Serialization
    Byte Stream
    File / Network / Database / Cache

    What is Deserialization?

    Deserialization is the reverse process.

    code
    Byte Stream
    Deserialization
    Java Object

    Why Serialization?

    Serialization is widely used in enterprise systems.

    Examples

    • Session Replication
    • Distributed Systems
    • RMI
    • JMS
    • Object Caching
    • File Storage
    • Network Communication
    • Message Queues

    Java Serialization Architecture

    code
    Java Object
    ObjectOutputStream
    Byte Stream
    File / Socket / Database
    ObjectInputStream
    Java Object

    Serializable Interface

    To make a class serializable, implement the marker interface Serializable.

    code
    import java.io.Serializable;
    public class Employee
    implements Serializable{
    private int id;
    private String name;
    }

    Serializable is a marker interface—it contains no methods.

    Serializing an Object

    code
    Employee employee =
    new Employee(
    101,
    "Rahul"
    );
    ObjectOutputStream output =
    new ObjectOutputStream(
    new FileOutputStream(
    "employee.ser"
    )
    );
    output.writeObject(employee);
    output.close();

    This writes the object to the file employee.ser.

    Deserializing an Object

    code
    ObjectInputStream input =
    new ObjectInputStream(
    new FileInputStream(
    "employee.ser"
    )
    );
    Employee employee =
    (Employee)
    input.readObject();
    System.out.println(employee);
    input.close();

    Complete Example

    code
    public class Employee
    implements Serializable{
    private int id;
    private String name;
    public Employee(
    int id,
    String name){
    this.id = id;
    this.name = name;
    }
    @Override
    public String toString(){
    return id + " " + name;
    }
    }

    Output after deserialization

    code
    101 Rahul

    serialVersionUID

    Every serializable class has a version identifier.

    code
    private static final long
    serialVersionUID = 1L;

    Purpose

    • Version Control
    • Compatibility Checking
    • Prevent Invalid Deserialization

    Why serialVersionUID?

    Suppose Version 1

    code
    class Employee{
    int id;
    }

    Later

    code
    class Employee{
    int id;
    String department;
    }

    Without a matching serialVersionUID, deserialization may fail with an InvalidClassException.

    transient Keyword

    Sometimes certain fields should not be serialized.

    Example

    code
    public class Employee
    implements Serializable{
    private String name;
    private transient String password;
    }

    Serialization

    code
    name
    ✔ Stored
    password
    ✘ Ignored

    After deserialization

    code
    System.out.println(
    employee.getPassword()
    );

    Output

    code
    null

    Use transient for:

    • Passwords
    • OTPs
    • API Keys
    • Authentication Tokens
    • Temporary Data

    static Fields

    Static fields belong to the class, not the object.

    code
    private static int counter;

    Static fields are not serialized.

    Custom Serialization

    Override writeObject().

    code
    private void writeObject(
    ObjectOutputStream out)
    throws IOException{
    out.defaultWriteObject();
    }

    Custom Deserialization

    Override readObject().

    code
    private void readObject(
    ObjectInputStream in)
    throws IOException,
    ClassNotFoundException{
    in.defaultReadObject();
    }

    Useful for validation, encryption, or backward compatibility.

    Object Graph Serialization

    If an object references another serializable object, the entire object graph is serialized.

    code
    class Employee
    implements Serializable{
    Address address;
    }

    Address must also implement Serializable.

    Serialization Memory Diagram

    code
    Employee Object
    ├── id
    ├── name
    └── Address
    ├── city
    └── state
    Byte Stream

    Serialization Process

    code
    Java Object
    Serializable Check
    ObjectOutputStream
    Byte Stream
    Storage

    Deserialization Process

    code
    Byte Stream
    ObjectInputStream
    Class Loading
    Object Creation
    Field Restoration

    Serialization Exceptions

    Common exceptions

    • NotSerializableException
    • InvalidClassException
    • ClassNotFoundException
    • IOException
    • EOFException

    Always handle these appropriately.

    Serialization in Spring Boot

    Serialization is used for

    • HTTP Sessions
    • Redis Cache
    • Distributed Sessions
    • Messaging
    • Event Processing

    However, modern Spring Boot applications often prefer JSON or Protocol Buffers for service-to-service communication instead of native Java Serialization.

    Java Serialization vs JSON

    Java SerializationJSON
    Binary FormatText Format
    Java SpecificLanguage Independent
    Smaller SizeMore Readable
    Faster in some JVM-only scenariosEasier Integration
    Security ConcernsWidely Used in REST APIs

    Serialization Security

    Native Java Serialization can be dangerous if deserializing untrusted data.

    Potential risks

    • Remote Code Execution
    • Gadget Chains
    • Object Injection
    • Denial of Service

    Never deserialize data from an untrusted source without proper validation or filtering.

    Best Practices

    Always Declare serialVersionUID

    Provides explicit version control.

    Use transient for Sensitive Data

    Examples

    • Passwords
    • Secrets
    • Tokens

    Prefer JSON for APIs

    Use libraries like Jackson for REST communication.

    Validate During Deserialization

    Perform integrity and security checks when reading serialized data.

    Use Try-with-Resources

    code
    try(ObjectOutputStream out =
    new ObjectOutputStream(
    new FileOutputStream(
    "employee.ser"
    ))){
    out.writeObject(employee);
    }

    Resources close automatically.

    Keep Serializable Classes Stable

    Frequent structural changes can break compatibility.

    Common Mistakes

    Forgetting Serializable

    code
    class Employee{
    }

    Throws

    code
    NotSerializableException

    Missing serialVersionUID

    May cause version compatibility problems.

    Serializing Sensitive Fields

    Protect confidential information using transient.

    Assuming Static Fields are Serialized

    Static members are ignored.

    Deserializing Untrusted Data

    Never deserialize data from unknown or untrusted sources without safeguards.

    Hands-on Exercise

    Create a Java program that:

    1. Creates an Employee class implementing Serializable.
    2. Serializes an object to a file.
    3. Deserializes the object.
    4. Declares serialVersionUID.
    5. Uses the transient keyword.
    6. Demonstrates that static fields are not serialized.
    7. Implements custom writeObject().
    8. Implements custom readObject().
    9. Serializes an object graph containing Employee and Address.
    10. Compares Java Serialization with JSON serialization using Jackson.

    Summary

    Java Serialization is the mechanism for converting Java objects into byte streams and restoring them later through deserialization. It enables object persistence, session replication, caching, and inter-JVM communication. While Serialization remains important for understanding legacy systems and JVM-specific use cases, modern enterprise applications often prefer JSON, Protocol Buffers, or other language-neutral formats for external communication due to better interoperability and improved security.

    Key Takeaways

    • Serialization converts objects into byte streams.
    • Deserialization reconstructs objects from byte streams.
    • Implement the Serializable interface to enable serialization.
    • ObjectOutputStream writes objects.
    • ObjectInputStream reads objects.
    • serialVersionUID controls version compatibility.
    • transient excludes sensitive fields from serialization.
    • Static fields are not serialized.
    • Native Java Serialization should not be used with untrusted data.
    • JSON is generally preferred for REST APIs and cross-platform communication.

    Professional Interview Questions

    1What is Serialization in Java?

    Professional Answer

    Serialization is the process of converting a Java object into a byte stream so that it can be stored, transferred over a network, or cached. Deserialization reconstructs the original object from the byte stream. Java supports this through the Serializable marker interface and the ObjectOutputStream and ObjectInputStream classes.

    Follow-up Questions

    • Which interface enables serialization?
    • What classes perform serialization and deserialization?

    Interview Tip: Object → Byte Stream → Object.

    2What is the purpose of serialVersionUID?

    Professional Answer

    serialVersionUID is a version identifier for a serializable class. During deserialization, the JVM verifies that the sender and receiver of a serialized object have compatible class definitions. Declaring an explicit serialVersionUID helps maintain version compatibility and prevents unexpected InvalidClassException errors when class definitions evolve.

    Follow-up Questions

    • What happens if serialVersionUID changes?
    • Should you always declare it explicitly?

    Interview Tip: serialVersionUID = Version Number for Serialized Objects.

    3Why is native Java Serialization discouraged for modern distributed applications?

    Professional Answer

    Native Java Serialization is Java-specific, can expose applications to deserialization security vulnerabilities if untrusted data is processed, and is not interoperable with other programming languages. Modern distributed systems typically use JSON, Protocol Buffers, Avro, or similar serialization formats because they are language-independent, easier to version, and more suitable for APIs and microservices.

    Follow-up Questions

    • Why do REST APIs commonly use JSON instead?
    • What security risks are associated with Java Serialization?

    Interview Tip: Java Serialization → JVM-to-JVM / Legacy Use Cases, JSON / Protobuf → Modern Microservices & REST APIs.

    Ready to mark this lesson complete?Track your journey across the entire course.