← Back to Home

Serialization

Serialization in Java is the process of converting an object into a byte stream so that it can be stored (file, DB) or transmitted (network) and later reconstructed back into the same object (deserialization).

This is a high-frequency interview topic, especially around marker interfaces, serialVersionUID, and transient fields.

What Is Serialization?

  • Converts object → byte stream
  • Enables persistence and network transfer
  • Reverse process is deserialization
  • Implemented using Object Streams

Why Serialization Is Needed

  • Save object state to file
  • Send objects over network (RMI, sockets)
  • Cache objects
  • Session replication (web apps)

Key Interfaces & Classes

Marker Interface

java.io.Serializable

  • ✔ No methods
  • ✔ Marks a class as serializable

Object Streams

  • ObjectOutputStream → serialize
  • ObjectInputStream → deserialize

Basic Serialization Example

Serializable Class

import java.io.Serializable;
class Employee implements Serializable {
    int id;
    String name;
    Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }
}
          

Serialization (Object → File)

ObjectOutputStream oos =
    new ObjectOutputStream(new FileOutputStream("emp.ser"));
Employee e = new Employee(1, "Java");
oos.writeObject(e);
oos.close();
          

Deserialization (File → Object)

ObjectInputStream ois =
    new ObjectInputStream(new FileInputStream("emp.ser"));
Employee e = (Employee) ois.readObject();
ois.close();
✔ Object state restored
✔ New object created in memory
          

Important Rules of Serialization

  1. Class must implement Serializable
  2. All non-transient fields are serialized
  3. Static variables are NOT serialized
  4. Constructors are NOT called
  5. Parent class must be Serializable or have no-arg constructor

transient Keyword (Very Important)

Marks fields not to be serialized.

class User implements Serializable {
    String username;
    transient String password;
}
✔ password not stored
✔ Value becomes default (null) after deserialization
          

serialVersionUID (Interview Favorite)

Used for version control of serialized classes.

private static final long serialVersionUID = 1L;
          

Why Needed?

  • Ensures compatibility during deserialization
  • Prevents InvalidClassException
  • ✔ Always define explicitly
  • ✔ Best practice

What Happens If Class Changes?

Scenario Result
serialVersionUID unchanged Deserialization succeeds
serialVersionUID changed ❌ InvalidClassException
No UID defined JVM generates one

Serialization Process (Conceptual Flow)

Object
 ↓ writeObject()
Byte Stream
 ↓ readObject()
Object (New Instance)
          

Custom Serialization (Advanced)

Override default behavior:

private void writeObject(ObjectOutputStream oos) throws IOException {
    oos.defaultWriteObject();
}
private void readObject(ObjectInputStream ois)
        throws IOException, ClassNotFoundException {
    ois.defaultReadObject();
}
✔ Used for encryption, validation, custom logic
          

Serialization vs Externalization

Aspect Serializable Externalizable
Control Less Full
Methods None writeExternal, readExternal
Performance Slower Faster
Ease Easy Complex

Security Concerns (Real-World)

  • Serialized data can be tampered
  • Vulnerable to deserialization attacks
  • Avoid deserializing untrusted data
  • ✔ Use validation
  • ✔ Prefer JSON/XML for APIs

Common Beginner Mistakes

  • Forgetting to implement Serializable
  • Not defining serialVersionUID
  • Expecting static fields to serialize
  • Assuming constructors run
  • Serializing sensitive data without transient

Best Practices (Production-Grade)

  • Always define serialVersionUID
  • Use transient for sensitive fields
  • Avoid Java serialization for APIs
  • Prefer JSON (Jackson) or Protobuf
  • Validate deserialized objects

Interview-Ready Answers

Short Answer

Serialization converts an object into a byte stream for storage or transmission.

Detailed Answer

In Java, serialization is the process of converting an object into a byte stream using ObjectOutputStream so that it can be persisted or sent over a network. The class must implement Serializable, and deserialization reconstructs the object using ObjectInputStream. Fields marked transient are not serialized, and serialVersionUID ensures version compatibility.

Key Takeaway

Serialization = Object persistence & transport. Powerful but risky—use carefully, define serialVersionUID, and avoid for public APIs unless required.