Detailed Explanation of Java Serialization and Deserialization - Notes By ShariqSP

Detailed Explanation of Java Serialization and Deserialization

Serialization and deserialization in Java allow objects to be converted into a stream of bytes for storage or transmission and then reconstructed back into objects. This mechanism is essential for tasks like saving objects to a file, transferring them over a network, or persisting their state. Here's an in-depth explanation of the concepts, classes, and methods involved.

Serialization in Java

Serialization is the process of converting an object's state into a byte stream. This stream can then be saved to a file, transmitted over a network, or stored in a database. Java provides the Serializable interface and associated classes for this process.

Classes and Methods for Serialization

  • Serializable:
    • A marker interface (has no methods) that must be implemented by a class to indicate that its objects can be serialized.
    • For example:
      public class Employee implements Serializable {
                      private int id;
                      private String name;
                  }
  • FileOutputStream:
    • A class used to create a file and write raw byte data to it.
    • Constructor: FileOutputStream(String fileName).
    • For example:
      FileOutputStream fileOut = new FileOutputStream("employee.ser");
  • ObjectOutputStream:
    • A class used to write Java objects to an output stream in a serialized form.
    • Constructor: ObjectOutputStream(OutputStream out).
    • Main method:
      • writeObject(Object obj): Writes the specified object to the output stream.
    • For example:
      ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
                  objectOut.writeObject(employee);

Deserialization in Java

Deserialization is the process of reconstructing an object from a serialized byte stream. This allows the object to be restored to its original state.

Classes and Methods for Deserialization

  • FileInputStream:
    • A class used to read raw byte data from a file.
    • Constructor: FileInputStream(String fileName).
    • For example:
      FileInputStream fileIn = new FileInputStream("employee.ser");
  • ObjectInputStream:
    • A class used to read objects from an input stream.
    • Constructor: ObjectInputStream(InputStream in).
    • Main method:
      • readObject(): Reads an object from the input stream and returns it.
    • For example:
      ObjectInputStream objectIn = new ObjectInputStream(fileIn);
                  Employee employee = (Employee) objectIn.readObject();

Complete Example of Serialization and Deserialization

import java.io.*;

            class Employee implements Serializable {
                private static final long serialVersionUID = 1L; // Ensures compatibility during serialization
                private int id;
                private String name;

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

                public String toString() {
                    return "Employee{id=" + id + ", name='" + name + "'}";
                }
            }

            public class SerializationDemo {
                public static void main(String[] args) {
                    Employee employee = new Employee(1, "John Doe");

                    // Serialization
                    try (FileOutputStream fileOut = new FileOutputStream("employee.ser");
                         ObjectOutputStream objectOut = new ObjectOutputStream(fileOut)) {
                        objectOut.writeObject(employee);
                        System.out.println("Object serialized successfully!");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    // Deserialization
                    try (FileInputStream fileIn = new FileInputStream("employee.ser");
                         ObjectInputStream objectIn = new ObjectInputStream(fileIn)) {
                        Employee deserializedEmployee = (Employee) objectIn.readObject();
                        System.out.println("Deserialized Object: " + deserializedEmployee);
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }

Key Points to Remember

  • Fields marked as transient are not serialized.
  • Always define a serialVersionUID in your class to ensure compatibility between serialized data and the class structure.
  • Objects of a class can only be serialized if all non-transient and non-static fields are serializable.
  • Custom serialization logic can be implemented by overriding writeObject and readObject methods.