Understanding Java Serialization and Deserialization

In this article, we will explore Java serialization and deserialization concepts through practical examples. You'll learn how to convert Java objects into a byte stream and back, allowing for easy storage and transmission.
By Jamie

What is Serialization?

Serialization in Java is the process of converting an object into a byte stream, which can then be saved to a file or sent over a network. This is particularly useful for persisting the state of an object or transferring it between different systems.

Basic Serialization Example

To demonstrate serialization, we will create a simple Java class, Person, and serialize an instance of it.

Step 1: Create the Person Class

import java.io.Serializable;

public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Step 2: Serialize the Object

Next, we will serialize an instance of Person to a file.

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

public class SerializeExample {
    public static void main(String[] args) {
        Person person = new Person("Alice", 30);
        try (FileOutputStream fileOut = new FileOutputStream("person.ser");
             ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
            out.writeObject(person);
            System.out.println("Serialized data is saved in person.ser");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

What is Deserialization?

Deserialization is the reverse process, where the byte stream is converted back into a Java object. This allows you to retrieve the original object’s state from a stored format.

Basic Deserialization Example

Now, let’s read the serialized object from the file and deserialize it.

Step 1: Deserialize the Object

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

public class DeserializeExample {
    public static void main(String[] args) {
        Person person = null;
        try (FileInputStream fileIn = new FileInputStream("person.ser");
             ObjectInputStream in = new ObjectInputStream(fileIn)) {
            person = (Person) in.readObject();
            System.out.println("Deserialized Person...");
            System.out.println("Name: " + person.getName());
            System.out.println("Age: " + person.getAge());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Summary

In this article, we covered the concepts of serialization and deserialization in Java with clear examples. By understanding these processes, you can effectively manage object state and facilitate data transfer in your applications.