Afzal Badshah, PhD

Understanding Serialization in Java: A Beginner’s Guide

Serialization is an important concept in Java, especially when you need to save the state of objects or transfer them over a network. In this tutorial, we’ll discuss how serialization and deserialization work in Java using a simple Car class. The process of serialization allows you to save the state of an object to a file, while deserialization allows you to read that object back into memory. Here, we will explore the steps of serializing and deserializing an Car object.

We begin with a Car class, which implements the Serializable interface. This is essential because Java needs to know that the objects of this class can be converted to a byte stream and saved to a file.

import java.io.*;

// Simple Car class implementing Serializable
class Car implements Serializable {
    String make;
    int year;

    Car(String make, int year) {
        this.make = make;
        this.year = year;
    }
}

public class CarSerializableExample {
    public static void main(String[] args) throws Exception {
        // Writing the object (Serialization)
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("car.txt"));
        Car car1 = new Car("Toyota", 2021);
        out.writeObject(car1);
        out.close();
        
        // Reading the object (Deserialization)
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("car.txt"));
        Car readCar = (Car) in.readObject();
        in.close();

        System.out.println("Car Make: " + readCar.make);
        System.out.println("Car Year: " + readCar.year);
    }
}

In this example, the Car class implements Serializable, indicating that its objects can be serialized. The Car class has two attributes: make (the car’s make) and year (the car’s manufacturing year). We provide a constructor to initialize these values.

Serialization process

Serialization Process

Serialization is the process of converting an object into a stream of bytes so that it can be saved to a file or transferred. In this example, we use the ObjectOutputStream to serialize the object and write it to a file.

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("car.txt"));
Car car1 = new Car("Toyota", 2021);
out.writeObject(car1);
out.close();

Deserialization Process

Deserialization is the opposite of serialization. It reads the byte stream from the file and converts it back into an object. In our example, we use ObjectInputStream to deserialize the object.

ObjectInputStream in = new ObjectInputStream(new FileInputStream("car.txt"));
Car readCar = (Car) in.readObject();
in.close();

Output

After deserialization, we can access the attributes of the Car object and print them to the console:

System.out.println("Car Make: " + readCar.make);
System.out.println("Car Year: " + readCar.year);

Exit mobile version