Serialization

Learn how to save the state of an object in Java using Serialization.

Java Serialization

Serialization is the process of converting an object's state into a byte stream, which can be persisted to a file, database, or sent over a network. The reverse process is called deserialization.

Why Serialization?

  • Persistence: Save the state of an object to a file.
  • Communication: Send objects over a network between different JVMs.
  • Deep Copy: Create an exact copy of an object.

The Serializable Interface

To make a class serializable, it must implement the java.io.Serializable interface. This is a marker interface (it has no methods).

import java.io.Serializable;

class Student implements Serializable {
    private static final long serialVersionUID = 1L;
    int id;
    String name;

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

Tip 💡

Always declare a serialVersionUID to ensure version compatibility during deserialization.

The transient Keyword

If you don't want to save a specific field (like a password), use the transient keyword.

class User implements Serializable {
    String username;
    transient String password; // This will NOT be serialized
}

Security Warning ⚠️

Deserialization is a common security vulnerability. Never deserialize data from untrusted sources. Attackers can craft malicious byte streams that execute code when deserialized.