Skip to content
C

Deserialization

Deserialization is the reverse of serialization — it converts a previously saved stream of bytes back into a usable Java object, restoring its original data.


1. What is Deserialization?

Deserialization is the reverse of serialization — it converts a previously saved stream of bytes back into a usable Java object, restoring its original data.

2. Why is it used?

Once an object has been serialized (saved), deserialization is needed to bring that saved data back into an actual, working object again, so the program can use it just like before.

3. Real-Life Example

Continuing the furniture example, deserialization is like unpacking that flat-packed box and reassembling the furniture back into its original, usable form.

4. Syntax

java
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.ser")); ClassName obj = (ClassName) in.readObject();

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 DeserializationDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.ser")); Student s = (Student) in.readObject(); in.close(); System.out.println("Name: " + s.name + ", Age: " + s.age); } }

Output:

Name: Aditi, Age: 21

(This assumes "student.ser" was already created using the serialization example above.)

6. Key Points to Remember

  • The class being deserialized must be available and match closely with the class used during serialization.
  • readObject() requires a cast back to the original class type, since it returns a general Object.
  • Mismatches between the saved object's class version and the current class definition can cause errors during deserialization.