What is Serialization and Deserialization?

In Java (and many other programming languages), serialization and deserialization are techniques used to convert objects into a format that can be easily saved or transferred—and then later restored.

📦 Serialization

Serialization is the process of converting a Java object into a stream of bytes. This is useful when you want to:

  • Save an object to a file
  • Send an object over a network
  • Store an object in a database

Once it’s serialized, it can be stored or transferred easily.

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
out.writeObject(myObject); // Converts the object to bytes
out.close();

⚠️ The class must implement Serializable to be eligible for serialization:

class MyData implements Serializable { int id; String name; }

💾 Deserialization

Deserialization is the reverse—it reconstructs the object from its byte-stream form.

ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.ser")); MyData obj = (MyData) in.readObject(); // Recreates the object 
in.close();

🛡 Pro Tip: If a class changes (e.g., new fields are added) after serialization, you may get compatibility issues. That’s where a serialVersionUID can help maintain version control.

Leave a Reply

Your email address will not be published. Required fields are marked *