File Handling & JDBC · Lesson 109 of 150
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.
01What 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.
02Why 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.
03Real-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.
04Syntax
javaclass ClassName implements Serializable { // fields } ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser")); out.writeObject(objectName);
05Example Program
javaimport 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.