Skip to content

Serialization

Serialization is the process of converting a Java object into a stream of bytes so it can be stored, transferred, or reconstructed later. Think of it as flattening an object into a portable format 📦


🧠 Why Serialization is Needed

  • Save object state to file
  • Send objects over network (APIs, sockets, RMI)
  • Cache data (Redis, disk)
  • Maintain session state in distributed systems

🔁 Deserialization

The reverse process: converting byte stream back into an object.


📦 Basic Example

🔹 Step 1: Make Class Serializable

import java.io.Serializable;

class Person implements Serializable {
    private static final long serialVersionUID = 1L;

    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

🔹 Step 2: Serialize Object

import java.io.*;

Person p = new Person("Swapnil", 25);

ObjectOutputStream out =
    new ObjectOutputStream(new FileOutputStream("person.ser"));

out.writeObject(p);
out.close();

🔹 Step 3: Deserialize Object

ObjectInputStream in =
    new ObjectInputStream(new FileInputStream("person.ser"));

Person p = (Person) in.readObject();
in.close();

System.out.println(p.name);

🔑 Important Concepts

🔹 Serializable Interface

👉 Serializable

  • Marker interface (no methods)
  • Enables object serialization

🔹 serialVersionUID

private static final long serialVersionUID = 1L;
  • Ensures compatibility during deserialization
  • Prevents InvalidClassException

🔹 transient Keyword

transient String password;
  • Field is not serialized
  • Used for sensitive or unnecessary data

🔹 Static Fields

  • Not serialized (belong to class, not object)

⚠️ Important Rules

  • Object must implement Serializable
  • All non-transient fields should also be serializable
  • Version mismatch can break deserialization

📊 Real-World Usage

  • Session replication in distributed apps
  • Messaging systems (Kafka, queues)
  • File storage
  • Caching

⚠️ Drawbacks

  • Slower compared to JSON/Protobuf
  • Security risks (deserialization attacks)
  • Tight coupling with class structure

🎯 Interview Answer

Serialization is the process of converting an object into a byte stream for storage or transmission, and deserialization is the reverse process. It is implemented using the Serializable interface and is commonly used in file handling, networking, and distributed systems.