C

Core Java tutorial for beginners

Clean • Professional

Serialization & Deserialization in Java (With Examples)

3 minute

Serialization & Deserialization in Java

Serialization and Deserialization are mechanisms in Java that allow objects to be converted to bytes and restored back to objects. They are mainly used for saving object data, transferring objects over networks, caching, and deep cloning.

What is Serialization?

Serialization is the process of converting a Java object into a byte stream.

This byte stream can then be:

  • Saved to a file
  • Stored in a database
  • Sent over a network
  • Cached
  • Transferred between JVMs

Serialization allows the object’s state to be preserved.

Basic Example of Serialization

import java.io.*;

class Student implements Serializable {
    int id;
    String name;

    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

public class SerializeExample {
    public static void main(String[] args) {
        Student s = new Student(101, "Durgesh");

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"))) {
            oos.writeObject(s);
            System.out.println("Object serialized successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How to Make a Class Serializable?

To serialize an object, the class must implement:

class Student implements Serializable { }

What is Deserialization?

Deserialization is the reverse process — converting a byte stream back into an actual Java object.

This restores the object into memory with the same values that it had when serialized.

Deserialization Example

import java.io.*;

public class DeserializeExample {
    public static void main(String[] args) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.ser"))) {
            Student s = (Student) ois.readObject();
            System.out.println("ID: " + s.id);
            System.out.println("Name: " + s.name);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Important Rules of Serialization

A) Fields marked transient are NOT serialized

Used for sensitive or temporary data.

transient String password;

B) Static fields are NOT serialized

Because they belong to the class, not the object.

C) Class should have a serialVersionUID

To avoid version mismatch errors.


serialVersionUID

Used to verify that a serialized object matches the class definition.

private static final long serialVersionUID = 1L;

If missing, JVM auto-generates it (not recommended).


Custom Serialization (writeObject/readObject)

You can customize how objects are serialized:

private void writeObject(ObjectOutputStream oos) throws Exception {
    oos.defaultWriteObject();
}

private void readObject(ObjectInputStream ois) throws Exception {
    ois.defaultReadObject();
}

When Serialization Fails?

  • Class does not implement Serializable
  • Field inside the class is not serializable (solution → mark it transient)
  • serialVersionUID mismatch

Serialization Real-World Use Cases

1. Save Application State

Example: Game progress, UI state, form data.

2. Transfer Objects Over Network

Used in:

  • RMI (Remote Method Invocation)
  • Socket programming
  • Microservices communication (legacy)

3. Store Objects in Files or Databases

Storing user profiles, logs, sessions.

4. Caching Objects

Frameworks like Ehcache store serialized objects.

5. Deep Cloning of Objects

Serialize → Deserialize → Get new copy.


Advantages of Serialization

  • Easy to save/restore objects
  • Helps in distributed systems
  • Good for caching
  • Supports deep cloning
  • Works automatically using default mechanism
  • Simple and easy to implement

Disadvantages of Serialization

  • Slow for large objects
  • Produces bigger byte streams compared to JSON/Binary protocols
  • Not language-independent
  • Hard to maintain across versions
  • Security issues (deserialization attacks)
  • Tight coupling between sender and receiver

Article 0 of 0