← Back to Chapters

Java Serialization

? Java Serialization

? Quick Overview

Serialization in Java is the process of converting an object into a byte stream so it can be saved to a file, sent over a network, or stored in memory. Deserialization is the reverse process of reconstructing the object from the byte stream.

? Key Concepts

  • Uses Serializable interface
  • Converts objects into a byte stream
  • Supports file storage and network transfer
  • Handles object state persistence

? Syntax / Theory

A class must implement the Serializable interface to allow its objects to be serialized. This interface is marker-based and does not contain any methods.

? Code Example(s)

? View Code Example
// Serializable class definition
import java.io.Serializable;

class Student implements Serializable {
    int id;
    String name;

    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
}
? View Code Example
// Serialization process
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializeDemo {
    public static void main(String[] args) throws Exception {
        Student s1 = new Student(101, "Amit");
        FileOutputStream fout = new FileOutputStream("student.ser");
        ObjectOutputStream out = new ObjectOutputStream(fout);
        out.writeObject(s1);
        out.close();
        fout.close();
    }
}

? Live Output / Explanation

The object Student is converted into a byte stream and stored in a file named student.ser. This file can later be used to restore the object.

? Interactive Simulator

Fill the object fields below and click Serialize to see how Java converts data into bytes. Use the transient checkbox to see how data is ignored.

☕ Java Object (RAM)

⬇️

✅ Tips & Best Practices

  • Use transient keyword to skip fields from serialization
  • Always define serialVersionUID for version control
  • Close streams properly to avoid memory leaks

? Try It Yourself

  • Add deserialization code to read the object back
  • Mark a variable as transient and observe behavior
  • Serialize multiple objects in a single file