← Back to Chapters

Java Deserialization

? Java Deserialization

? Quick Overview

Deserialization in Java is the process of converting a byte stream back into a live Java object. It is the reverse of serialization and is commonly used when reading objects from files, databases, or network streams.

? Key Concepts

  • Reconstructs objects from byte streams
  • Uses ObjectInputStream
  • Class must implement Serializable
  • Maintains object state

? Syntax / Theory

During deserialization, the JVM recreates the object without calling constructors. The class definition must be available in the classpath for successful deserialization.

? Code Example

? View Code Example
// Deserializing an object from a file
import java.io.*;

class Student implements Serializable {
String name;
int age;
}

public class DeserializeDemo {
public static void main(String[] args) throws Exception {
ObjectInputStream in=new ObjectInputStream(new FileInputStream("student.ser"));
Student s=(Student)in.readObject();
in.close();
System.out.println(s.name+" "+s.age);
}
}

? Interactive Simulation

Simulate the cycle to see how the transient keyword affects deserialization.

1. Original Java Object (Heap)

Object: { name: "Alice", age: 22 }
⬇️
⬇️

? Live Output / Explanation

Output

The program reads the serialized object from student.ser and restores the Student object with its original values.

✅ Tips & Best Practices

  • Always match serialVersionUID during serialization and deserialization
  • Close streams to avoid memory leaks
  • Validate data before deserializing from untrusted sources

? Try It Yourself

  • Create your own class and serialize it
  • Modify class structure and observe deserialization behavior
  • Experiment with transient variables