What Is Serialization in Java and How Does Deserialization Work?

Learn What Is Serialization in Java and How Does Deserialization Work? with practical examples, explanations, best practices, and real-world coding techniques.

Java Serialization is the process of converting the state of a Java object into a sequence of bytes so that the object can be stored or transferred. Deserialization is the reverse process: reading those bytes and reconstructing the object in memory. Java serialization is commonly associated with the Serializable interface, ObjectOutputStream, and ObjectInputStream.

A useful way to understand the idea is to think about saving a Java object's current state. Suppose an application creates a Ticket object containing a passenger name, source, destination, and price. Serialization can turn that object's state into bytes that can be written to a file or another byte-oriented destination. Later, those bytes can be read and converted back into a Java object through deserialization.

Serialization vs Deserialization

Operation Purpose Common Java Class
Serialization Object → byte stream ObjectOutputStream
Deserialization Byte stream → object ObjectInputStream

What Is Java Serialization?

Java serialization captures the serializable state of an object and writes it to an output stream. The object can then be persisted in a file or passed through another byte-oriented mechanism. The Java object itself is not simply written as readable source code. Its state is represented in a binary form.

A class usually participates in standard Java serialization by implementing the java.io.Serializable interface. Serializable is a marker interface, which means it does not require the class to implement methods. It signals that instances of the class are eligible for the default Java object serialization mechanism.

import java.io.Serializable;

class Ticket implements Serializable {
    private String passengerName;
    private String source;
    private String destination;
}

How Object Serialization Works

The basic flow is straightforward:

1. Create Object

Your application creates a normal Java object and fills it with data.

2. Serialize

ObjectOutputStream writes the object's state to a byte stream.

3. Restore

ObjectInputStream reads the stream and reconstructs the object.

Java Object → Byte Stream → File / Storage / Stream → Byte Stream → Java Object

Serializing an Object with ObjectOutputStream

The most common API for writing serializable Java objects is ObjectOutputStream. It can be layered over another output stream such as FileOutputStream.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Ticket implements Serializable {

    private static final long serialVersionUID = 1L;

    private String passengerName;
    private String source;
    private String destination;
    private double price;

    public Ticket(
            String passengerName,
            String source,
            String destination,
            double price) {

        this.passengerName = passengerName;
        this.source = source;
        this.destination = destination;
        this.price = price;
    }

    @Override
    public String toString() {
        return passengerName + " | "
                + source + " -> "
                + destination + " | ₹"
                + price;
    }
}

public class SerializeExample {

    public static void main(String[] args) {

        Ticket ticket = new Ticket(
                "Ananya",
                "Mumbai",
                "Pune",
                450.0
        );

        try (
            FileOutputStream fileOut =
                    new FileOutputStream("ticket.ser");

            ObjectOutputStream objectOut =
                    new ObjectOutputStream(fileOut)
        ) {

            objectOut.writeObject(ticket);

            System.out.println(
                    "Ticket serialized successfully."
            );

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The important operation here is writeObject(). It takes the object and writes its serializable state to the underlying stream. The .ser extension is commonly used for serialized object files, although Java does not require that particular file extension.

Deserializing an Object with ObjectInputStream

Deserialization uses ObjectInputStream. The readObject() method reads the serialized representation and reconstructs an object. Because readObject() returns Object, the result is commonly assigned to the expected type after an appropriate cast.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializeExample {

    public static void main(String[] args) {

        try (
            FileInputStream fileIn =
                    new FileInputStream("ticket.ser");

            ObjectInputStream objectIn =
                    new ObjectInputStream(fileIn)
        ) {

            Ticket ticket =
                    (Ticket) objectIn.readObject();

            System.out.println("Passenger: "
                    + ticket.getPassengerName());

            System.out.println("From: "
                    + ticket.getSource());

            System.out.println("To: "
                    + ticket.getDestination());

            System.out.println("Price: ₹"
                    + ticket.getPrice());

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

In a real application, the Ticket class should expose appropriate methods such as getters or domain behavior rather than making all state publicly accessible. The key idea remains the same: serialized bytes are read and converted back into an object.

What Is serialVersionUID?

serialVersionUID is a version identifier used during Java serialization. It helps the deserialization process determine whether the serialized representation is compatible with the current class definition.

private static final long serialVersionUID = 1L;

Explicitly declaring a serialVersionUID makes the intended serialization version easier to control. If the class changes in a way that is incompatible with previously serialized data, deserialization can fail with InvalidClassException.

This is particularly relevant when serialized data survives longer than the application process itself, such as files, caches, or stored application state.

The transient Keyword

Sometimes a field should not be included in the serialized state. Java provides the transient keyword for this purpose.

A transient field is skipped by the default serialization mechanism. When an object is deserialized, that field receives its normal default value unless the class provides custom restoration logic.

import java.io.Serializable;

class UserSession implements Serializable {

    private static final long serialVersionUID = 1L;

    private String username;

    private transient String temporaryToken;

    public UserSession(
            String username,
            String temporaryToken) {

        this.username = username;
        this.temporaryToken = temporaryToken;
    }

    public void printData() {
        System.out.println("Username: " + username);
        System.out.println("Token: " + temporaryToken);
    }
}

The non-transient username participates in default serialization, while temporaryToken does not. This can be useful for temporary runtime state, derived information, or values that should not be persisted as part of the serialized form.

Which Fields Are Serialized?

With default Java serialization, the serializable state of an object includes its non-static, non-transient fields. Static fields belong to the class rather than a particular object instance, so they are not serialized as instance state.

Field Default Serialization
Normal instance field Included when serializable
transient field Excluded
static field Not part of instance state
Object reference Requires a compatible serializable object graph

Serializable Object Graphs

Serialization does not only consider the top-level object. It follows references to objects that form the object's reachable state. Those referenced objects generally also need to support serialization when they are part of the serialized graph.

Order → Customer → Address

If Order contains a Customer reference and the customer contains an Address reference, serialization may traverse those objects as part of the object graph.

A common problem occurs when one referenced object is not serializable. In that situation, attempting to serialize the graph can result in a NotSerializableException.

Serialization and Inheritance

Serialization interacts with class inheritance in an important way. When a serializable subclass extends a non-serializable superclass, the superclass itself does not become serializable simply because the child implements Serializable. During default deserialization, the first non-serializable superclass is initialized using its accessible no-argument constructor.

This means inheritance hierarchies should be designed carefully when serialization is part of the application's data model. Serialized state and constructor behavior are not always equivalent.

Custom Serialization with writeObject and readObject

Java also allows a class to customize how its state is written and restored. A class can define private methods named writeObject and readObject with the appropriate signatures. These methods can be used to control serialization behavior while still using the normal object-stream mechanism.

private void writeObject(
        ObjectOutputStream out) throws IOException {

    out.defaultWriteObject();

    // Write additional custom state if required.
}

private void readObject(
        ObjectInputStream in)
        throws IOException, ClassNotFoundException {

    in.defaultReadObject();

    // Restore or validate custom state if required.
}

Custom serialization is useful when an object's persisted representation requires additional control, validation, compatibility handling, or special treatment of fields.

Serialization Is Not the Same as JSON

Java serialization and JSON serialization solve related but different problems. Java object serialization creates a Java-specific binary representation of object state. JSON represents data as a text-based interchange format that is commonly used by web APIs and systems written in different programming languages.

Java Serialization JSON Serialization
Java object-stream format Text-based data format
Strongly tied to Java object serialization Common for language-independent APIs
Uses ObjectOutputStream Often handled by libraries such as Jackson or Gson
Binary representation Human-readable text representation

Where Java Serialization Can Be Used

Persisting Object State

An application can serialize an object graph to a file and restore it later.

Caching

Serialized representations can be used as one form of cached application state, depending on the architecture.

Legacy Java Systems

Existing enterprise applications may contain APIs and stored data built around Java serialization.

Object Streams

Java applications can send serialized objects through compatible object streams.

Security Considerations

One of the most important things to understand about Java deserialization is that untrusted serialized data should not be deserialized blindly. Java object deserialization can reconstruct object graphs and can trigger class-specific behavior as part of the process. Deserializing attacker-controlled data has historically been associated with serious security vulnerabilities.

For this reason, avoid treating Java native serialization as a general-purpose data interchange format for untrusted input. For external APIs and cross-language communication, explicit data formats such as JSON are often a better fit. When native serialization is unavoidable, applications should apply appropriate filtering, validation, access controls, and trusted-input boundaries.

Important Security Rule

Never assume that serialized bytes are harmless simply because they came from a file, cache, network connection, or another system. Serialization is a data format, not a trust boundary.

Common Java Serialization Exceptions

NotSerializableException

Usually occurs when an object that must be serialized does not support the required serialization mechanism.

InvalidClassException

Can occur when the serialized representation is incompatible with the current class definition, including a serial version mismatch.

ClassNotFoundException

Can occur during deserialization when the JVM cannot resolve the class required to reconstruct the object.

Java Serialization Best Practices

  • Declare an explicit serialVersionUID when using Java serialization intentionally.
  • Use transient for state that should not be serialized as part of the default object state.
  • Keep serialized classes stable when serialized data needs to survive application upgrades.
  • Use try-with-resources for object streams and underlying file streams.
  • Do not deserialize untrusted or attacker-controlled data without appropriate safeguards.
  • Prefer explicit interchange formats such as JSON when systems or languages need to communicate through stable APIs.
  • Do not use serialization automatically for every persistence problem; database records and structured data formats are often more appropriate.

Practical Example: Save and Restore a User Profile

Consider a small desktop Java application that stores a user's preferences locally. A serializable UserProfile object could contain the username, selected theme, and other state. The application can serialize the profile when the user closes the application and deserialize it the next time the application starts.

import java.io.*;

class UserProfile implements Serializable {

    private static final long serialVersionUID = 1L;

    private final String username;
    private String theme;

    public UserProfile(String username, String theme) {
        this.username = username;
        this.theme = theme;
    }

    public String getUsername() {
        return username;
    }

    public String getTheme() {
        return theme;
    }

    public void setTheme(String theme) {
        this.theme = theme;
    }
}

public class ProfileStorage {

    private static final String FILE_NAME =
            "profile.ser";

    public static void save(UserProfile profile)
            throws IOException {

        try (ObjectOutputStream out =
                     new ObjectOutputStream(
                         new FileOutputStream(FILE_NAME))) {

            out.writeObject(profile);
        }
    }

    public static UserProfile load()
            throws IOException, ClassNotFoundException {

        try (ObjectInputStream in =
                     new ObjectInputStream(
                         new FileInputStream(FILE_NAME))) {

            return (UserProfile) in.readObject();
        }
    }

    public static void main(String[] args)
            throws Exception {

        UserProfile profile =
                new UserProfile("ananya", "dark");

        save(profile);

        UserProfile restored = load();

        System.out.println(
                restored.getUsername()
        );

        System.out.println(
                restored.getTheme()
        );
    }
}

Serialization vs Normal Object Creation

Deserialization should not be thought of as simply calling the class constructor again. The Java serialization mechanism reconstructs the serialized state according to the serialization protocol. This distinction becomes important when classes contain constructors, inherited state, transient fields, validation rules, or custom readObject() logic.

That is one reason serialization is a specialized mechanism rather than a general replacement for constructors, databases, or API DTOs.

Key Takeaways

Java Serialization converts a compatible Java object's state into a byte stream.

Deserialization reconstructs an object from that serialized representation.

Serializable, ObjectOutputStream, and ObjectInputStream form the core of the traditional Java object serialization API.

serialVersionUID helps control compatibility between serialized data and class definitions.

transient prevents a field from participating in default serialization.

Native Java deserialization requires careful security handling, especially when the serialized data does not come from a fully trusted source.

Code Examples

java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Ticket implements Serializable {

    private static final long serialVersionUID = 1L;

    private final String passengerName;
    private final String source;
    private final String destination;
    private final double price;

    public Ticket(
            String passengerName,
            String source,
            String destination,
            double price) {

        this.passengerName = passengerName;
        this.source = source;
        this.destination = destination;
        this.price = price;
    }

    @Override
    public String toString() {
        return passengerName + " | "
                + source + " -> "
                + destination
                + " | ₹"
                + price;
    }
}

public class SerializeExample {

    public static void main(String[] args) {

        Ticket ticket = new Ticket(
                "Ananya",
                "Mumbai",
                "Pune",
                450.0
        );

        try (
            FileOutputStream fileOut =
                    new FileOutputStream("ticket.ser");

            ObjectOutputStream out =
                    new ObjectOutputStream(fileOut)
        ) {

            out.writeObject(ticket);

            System.out.println(
                    "Ticket serialized successfully."
            );

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
    
java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializeExample {

    public static void main(String[] args) {

        try (
            FileInputStream fileIn =
                    new FileInputStream("ticket.ser");

            ObjectInputStream in =
                    new ObjectInputStream(fileIn)
        ) {

            Ticket ticket =
                    (Ticket) in.readObject();

            System.out.println(
                    "Restored ticket: " + ticket
            );

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
    
java
import java.io.*;

class Account implements Serializable {

    private static final long serialVersionUID = 1L;

    private String username;

    private transient String temporaryToken;

    public Account(String username, String temporaryToken) {
        this.username = username;
        this.temporaryToken = temporaryToken;
    }

    public void print() {
        System.out.println("Username: " + username);
        System.out.println("Token: " + temporaryToken);
    }
}

public class TransientExample {

    public static void main(String[] args)
            throws Exception {

        Account account =
                new Account("ananya", "TEMP-123");

        try (ObjectOutputStream out =
                     new ObjectOutputStream(
                         new FileOutputStream("account.ser"))) {

            out.writeObject(account);
        }

        try (ObjectInputStream in =
                     new ObjectInputStream(
                         new FileInputStream("account.ser"))) {

            Account restored =
                    (Account) in.readObject();

            restored.print();
        }
    }
}
    

Pro Tip

Use Java serialization deliberately rather than automatically. For modern application-to-application communication, APIs, and long-term data interchange, prefer explicit and well-defined formats such as JSON when they better match the requirement. When native Java serialization is required, define serialVersionUID carefully, keep object graphs controlled, and treat deserialization of external data as a security-sensitive operation.

More Advanced Java lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.