C

Core Java tutorial for beginners

Clean • Professional

Object Serialization Interfaces in Java Explained with Examples

2 minute

Object Serialization Interfaces in Java

Java provides two interfaces for object serialization:

learn code with durgesh images

  1. Serializable
  2. Externalizable

Both help convert objects into a byte stream, but they work very differently.

What is Serializable Interface

Serializable is a marker interface (no methods) that enables default serialization.

Example (Automatic):

public class Student implements Serializable {
    int id;
    String name;
}

Purpose

When a class implements Serializable, the JVM automatically:

  • Saves all non-transient, non-static fields
  • Handles the object graph (nested objects)
  • Restores it during deserialization

Features

  • No methods to implement
  • JVM handles serialization internally
  • Supports default serialization
  • Works with ObjectOutputStream / ObjectInputStream
  • Supports transient keyword
  • Uses serialVersionUID for versioning

When to Use Serializable?

  • When you want quick object saving
  • Perfect for simple Java objects (DTOs, Entities)
  • When performance/custom control is not required

What is Externalizable Interface

Externalizable is a subinterface of Serializable but gives full manual control over serialization.

Purpose

Used when you want to customize how objects are saved and restored.

It has two methods:

learn code with durgesh images

  • writeExternal()
  • readExternal()
public void writeExternal(ObjectOutput out) throws IOException;
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;

Example (Custom):

class Employee implements Externalizable {
    int id;
    String name;

    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeInt(id);
        out.writeUTF(name);
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        id = in.readInt();
        name = in.readUTF();
    }
}

Features

  • Manual serialization
  • Programmer controls what to save and restore
  • Faster in some cases because only required data is stored
  • Requires a public no-arg constructor

When to Use Externalizable?

  • When you need complete and efficient control
  • For large objects where performance matters
  • When you want to skip some fields without using transient
  • For custom binary formats / compact serialization

Serializable vs Externalizable

FeatureSerializableExternalizable
TypeMarker InterfaceInterface with methods
ControlJVM controls serializationDeveloper controls serialization
MethodsNoneMust implement writeExternal() & readExternal()
Default BehaviorYesNo (everything is manual)
PerformanceSlower (stores full object)Faster (store only needed fields)
transient SupportYesNot needed (manual control)
No-arg ConstructorNot requiredRequired

 

Article 0 of 0