Skip to content
C

Serialization

Serialization is the process of converting a Java object into a stream of bytes, so it can be saved to a file, sent over a network, or stored for later use, while preserving the object's data.


1. What is Serialization?

Serialization is the process of converting a Java object into a stream of bytes, so it can be saved to a file, sent over a network, or stored for later use, while preserving the object's data.

2. Why is it used?

It allows an object's current state to be saved permanently, or transferred elsewhere, and later restored back into a usable object — useful for saving application data, session information, or sending objects between systems.

3. Real-Life Example

Think of packing a fully assembled piece of furniture into a flat, compact box for shipping, so it can be transported and later reassembled elsewhere. Serialization "packs" an object into a storable, transferable form.

4. Syntax

java
class ClassName implements Serializable { // fields } ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser")); out.writeObject(objectName);

5. Example Program

java
import java.io.*; class Student implements Serializable { String name; int age; Student(String name, int age) { this.name = name; this.age = age; } } public class SerializationDemo { public static void main(String[] args) throws IOException { Student s = new Student("Aditi", 21); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.ser")); out.writeObject(s); out.close(); System.out.println("Object serialized successfully."); } }

Output:

Object serialized successfully.

6. Key Points to Remember

  • A class must implement the Serializable interface (a marker interface with no methods) to support serialization.
  • Fields marked as transient are skipped during serialization and won't be saved.
  • Serialized objects are typically saved with a .ser file extension by convention.