Object Serialization and Deserialization

Tutorial 4 of 5

1. Introduction

1.1 Tutorial's Goal

The goal of this tutorial is to introduce you to the concepts of object serialization and deserialization in Java.

1.2 What Will You Learn?

By the end of this tutorial, you will be able to understand the concepts of object serialization and deserialization in Java, write code to serialize and deserialize objects, and understand the use cases and best practices.

1.3 Prerequisites

Before starting this tutorial, you should have a basic understanding of Java, including knowledge of Java classes and objects.

2. Step-by-Step Guide

2.1 Concepts

Serialization is the process of converting an object's state to a byte stream, and it's primarily used in networking programming and RMI (Remote Method Invocation), while deserialization is the reverse process of creating an object from a byte stream.

2.2 Examples

Serialization

To serialize an object, we will use ObjectOutputStream.

FileOutputStream fileOutputStream = new FileOutputStream("ser.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(object);
objectOutputStream.close();

Deserialization

To deserialize an object, we will use ObjectInputStream.

FileInputStream fileInputStream = new FileInputStream("ser.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
MyClass object = (MyClass) objectInputStream.readObject();
objectInputStream.close();

2.3 Best Practices and Tips

  1. Always close the stream after use to avoid memory leaks.
  2. The class whose objects are to be serialized should implement Serializable interface.

3. Code Examples

3.1 Serialization

import java.io.*;

class Employee implements Serializable {
    String name;
    int age;

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

public class SerializeExample {
    public static void main(String[] args) {
        Employee e = new Employee("John Doe", 30);
        try {
            FileOutputStream fileOut = new FileOutputStream("employee.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(e);
            out.close();
            fileOut.close();
        } catch (IOException i) {
            i.printStackTrace();
        }
    }
}

In the above code, we create an Employee class that implements Serializable interface. In the main method, we create an object of Employee, serialize it, and save it in "employee.ser".

3.2 Deserialization

import java.io.*;

public class DeserializeExample {
    public static void main(String[] args) {
        Employee e = null;
        try {
            FileInputStream fileIn = new FileInputStream("employee.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            e = (Employee) in.readObject();
            in.close();
            fileIn.close();
        } catch (IOException i) {
            i.printStackTrace();
            return;
        } catch (ClassNotFoundException c) {
            System.out.println("Employee class not found");
            c.printStackTrace();
            return;
        }
        System.out.println("Deserialized Employee...");
        System.out.println("Name: " + e.name);
        System.out.println("Age: " + e.age);
    }
}

In the above code, we deserialize the "employee.ser" file and read the Employee object from it.

4. Summary

In this tutorial, you learned about object serialization and deserialization in Java, wrote code to serialize and deserialize objects, and understood its use cases and best practices.

5. Practice Exercises

5.1 Exercise 1

Create a Student class with name, age, and grade attributes and serialize an object of this class.

5.2 Solution

import java.io.*;

class Student implements Serializable {
    String name;
    int age;
    int grade;

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

public class SerializeStudent {
    public static void main(String[] args) {
        Student s = new Student("John Doe", 16, 10);
        try {
            FileOutputStream fileOut = new FileOutputStream("student.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(s);
            out.close();
            fileOut.close();
        } catch (IOException i) {
            i.printStackTrace();
        }
    }
}

5.3 Exercise 2

Deserialize the "student.ser" file created in the previous exercise and read the Student object from it.

5.4 Solution

import java.io.*;

public class DeserializeStudent {
    public static void main(String[] args) {
        Student s = null;
        try {
            FileInputStream fileIn = new FileInputStream("student.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            s = (Student) in.readObject();
            in.close();
            fileIn.close();
        } catch (IOException i) {
            i.printStackTrace();
            return;
        } catch (ClassNotFoundException c) {
            System.out.println("Student class not found");
            c.printStackTrace();
            return;
        }
        System.out.println("Deserialized Student...");
        System.out.println("Name: " + s.name);
        System.out.println("Age: " + s.age);
        System.out.println("Grade: " + s.grade);
    }
}

In the code above, we are deserializing the "student.ser" file and reading the Student object from it.