Skip to content

Latest commit

 

History

History
100 lines (72 loc) · 3.1 KB

File metadata and controls

100 lines (72 loc) · 3.1 KB

Q12 — Serialization & Deserialization

Interview Tip: Show it working — write an object to a file, read it back. Mention serialVersionUID and transient in the same breath.


🔑 What is it?

  • Serialization → Convert Java object → byte stream (to save to file/send over network)
  • Deserialization → Convert byte stream → Java object (to restore it)

💻 Code — Run This Live

import java.io.*;

// Step 1: Class must implement Serializable
class Employee implements Serializable {

    private static final long serialVersionUID = 1L;  // version control

    private String name;
    private int age;
    private transient String password;   // transient = NOT serialized

    public Employee(String name, int age, String password) {
        this.name = name;
        this.age = age;
        this.password = password;
    }

    @Override
    public String toString() {
        return "Employee{name='" + name + "', age=" + age
               + ", password='" + password + "'}";
    }
}

public class SerializationDemo {

    public static void main(String[] args) throws Exception {

        Employee emp = new Employee("Dip", 28, "secret123");
        System.out.println("Before: " + emp);

        // SERIALIZATION — write to file
        ObjectOutputStream oos = new ObjectOutputStream(
                                    new FileOutputStream("employee.ser"));
        oos.writeObject(emp);
        oos.close();
        System.out.println("Serialized to employee.ser");

        // DESERIALIZATION — read from file
        ObjectInputStream ois = new ObjectInputStream(
                                    new FileInputStream("employee.ser"));
        Employee restored = (Employee) ois.readObject();
        ois.close();

        System.out.println("After:  " + restored);
        // Note: password will be null — transient field not serialized!
    }
}

Expected Output:

Before: Employee{name='Dip', age=28, password='secret123'}
Serialized to employee.ser
After:  Employee{name='Dip', age=28, password='null'}

📌 Key Points

  • Class must implement java.io.Serializable (marker interface — no methods)
  • serialVersionUID → version number; if class changes and UID doesn't match → InvalidClassException
  • transient → field is skipped during serialization (passwords, sensitive data)
  • static fields are also not serialized (they belong to class, not object)
  • Use case: HTTP session storage, caching, message queues, file persistence

📌 In Real Projects

Context Serialization Used
Spring Session Stores session object as bytes in Redis
Kafka Serializes message objects before sending
JPA Entities Should implement Serializable (best practice)
Java RMI Objects passed over network are serialized

🎯 Follow-Up Question

"What happens if you don't declare serialVersionUID?" → JVM auto-generates one based on class structure. If class changes (add a field), the UID changes → old serialized data becomes unreadable → InvalidClassException at runtime. Always declare it explicitly.