</>

Technology

Core Java

Difficulty

Intermediate

Interview Question

What is Serialization in Java? How do you implement it?

Answer

Serialization in Java

Serialization = converting a Java object into a byte stream (for storage/network transfer) Deserialization = converting byte stream back to an object

Why Serialization?

  • Save object state to a file or database
  • Send objects over a network (RMI, sockets)
  • Cache objects (Redis, memcached)
  • Deep copy of objects

Implementing Serialization

Java
import java.io.Serializable;

public class Employee implements Serializable {
    // Always define serialVersionUID for version control
    private static final long serialVersionUID = 1L;

    private String name;
    private String department;
    private int    age;
    private double salary;

    // transient — this field will NOT be serialized
    private transient String password;
    // static fields are also NOT serialized (belong to class, not instance)
    private static String companyName = "AutomateQA";

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

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

Serialize (Write to File)

Java
public static void serialize(Employee emp, String filePath) {
    try (ObjectOutputStream oos = new ObjectOutputStream(
             new FileOutputStream(filePath))) {
        oos.writeObject(emp);
        System.out.println("Serialized: " + emp.getName());
    } catch (IOException e) {
        throw new RuntimeException("Serialization failed", e);
    }
}

Employee emp = new Employee("Alice", "QA", 30, 95000, "secret123");
serialize(emp, "employee.ser");

Deserialize (Read from File)

Java
public static Employee deserialize(String filePath) {
    try (ObjectInputStream ois = new ObjectInputStream(
             new FileInputStream(filePath))) {
        return (Employee) ois.readObject();
    } catch (IOException | ClassNotFoundException e) {
        throw new RuntimeException("Deserialization failed", e);
    }
}

Employee loaded = deserialize("employee.ser");
System.out.println(loaded);
// Employee{name='Alice', dept='QA', age=30, salary=95000.0, password=null}
// Note: password is null — transient field not serialized

serialVersionUID — Version Control

Java
// Without explicit serialVersionUID, JVM generates one based on class structure
// If you change the class (add/remove fields) — JVM generates a NEW ID
// Deserialization fails with InvalidClassException!

// BEST PRACTICE: Always declare it explicitly
private static final long serialVersionUID = 1L;

// Use value = 2L when making BREAKING changes to the class
private static final long serialVersionUID = 2L;

transient Keyword

Java
public class UserSession implements Serializable {
    private static final long serialVersionUID = 1L;

    private String username;          // serialized
    private String sessionId;         // serialized
    private transient String token;   // NOT serialized (sensitive)
    private transient WebDriver driver; // NOT serialized (not serializable)
}

Externalizable Interface (Manual Control)

Java
// More control than Serializable — implement read/write yourself
public class Config implements Externalizable {
    private String host;
    private int    port;

    // Required no-arg constructor
    public Config() {}

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(host);
        out.writeInt(port);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        host = (String) in.readObject();
        port = in.readInt();
    }
}

In Automation Testing

Java
// Use serialization to save/restore test state
public class TestStateManager {
    public static void saveState(TestState state, String path) throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(
                 new FileOutputStream(path))) {
            oos.writeObject(state);
        }
    }

    public static TestState loadState(String path) throws Exception {
        try (ObjectInputStream ois = new ObjectInputStream(
                 new FileInputStream(path))) {
            return (TestState) ois.readObject();
        }
    }
}

Follow AutomateQA

Related Topics