Java Serialization

java

In Java, serialization is the process of converting an object’s state (including its variables) into a format that can be stored or transmitted, and deserialization is the process of creating an object from its serialized state. Serialization is useful for storing objects or transmitting them over a network, while deserialization is useful for creating objects from the stored or transmitted data.

To make a Java class serializable, you need to implement the Serializable interface. This interface does not have any methods, it is simply a marker interface that indicates that a class can be serialized. Here is an example of a serializable class:

import java.io.Serializable;

public class Person implements Serializable {
  private String name;
  private int age;

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

  // getters and setters go here
}

To serialize an object, you can use the ObjectOutputStream class and the writeObject() method. Here is an example of serializing an object to a file:

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

Person person = new Person("John Smith", 30);

try (FileOutputStream fos = new FileOutputStream("person.ser");
     ObjectOutputStream oos = new ObjectOutputStream(fos)) {
  oos.writeObject(person);
} catch (IOException e) {
  e.printStackTrace();
}

To deserialize an object, you can use the ObjectInputStream class and the readObject() method. Here is an example of deserializing an object from a file:

import java.io.FileInputStream;
import java.io.ObjectInputStream;

Person person = null;

try (FileInputStream fis = new FileInputStream("person.ser");
     ObjectInputStream ois = new ObjectInputStream(fis)) {
  person = (Person) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
  e.printStackTrace();
}

In this example, we have used the try-with-resources statement to ensure that the input streams are properly closed when we are finished using them.

Serialization is a useful feature in Java, as it allows you to store and transmit objects in a compact and portable format. However, it is important to be aware that not all objects can be serialized, and you need to take care to properly handle serialization and deserialization errors.