Java Serialization

Hello there, fellow coder! Today, we’re diving into the world of Java Serialization. Buckle up, because we’re about to embark on a journey of learning and discovery. Let’s get started!

Introduction to Java Serialization

Ever wondered how to turn a Java object into a bunch of bytes? Or maybe you’ve pondered how to reverse the process? Well, that’s where Java Serialization comes in. It’s a mechanism that turns an object into a byte stream, and the reverse process is called deserialization. This is super handy for saving an object’s state or sending it over a network. Cool, right?

Understanding the Java Serializable Interface

In Java, any class that you want to serialize must implement the java.io.Serializable interface. This interface is a marker interface, meaning it doesn’t actually contain any methods. It just tells the Java Virtual Machine (JVM) that your class is eligible for serialization. Easy peasy!

The Serialization Process

Serialization in Java is pretty straightforward. You use an ObjectOutputStream and its writeObject() method. But remember, only objects of classes that implement Serializable can be serialized. Let’s look at a simple example:

public class SerializeExample {
    public static void main(String[] args) {
        MyClass myClass = new MyClass();
        myClass.myMethod();

        try {
            FileOutputStream fileOut = new FileOutputStream("myClass.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(myClass);
            out.close();
            fileOut.close();
        } catch (IOException i) {
            i.printStackTrace();
        }
    }
}
Java

In this code, we’re serializing an object of MyClass. The serialized object is saved in a file named myClass.ser.

The Deserialization Process

Deserialization is just as easy as serialization. You use an ObjectInputStream and its readObject() method. Here’s how you do it:

public class DeserializeExample {
    public static void main(String[] args) {
        MyClass myClass = null;

        try {
            FileInputStream fileIn = new FileInputStream("myClass.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            myClass = (MyClass) in.readObject();
            in.close();
            fileIn.close();
        } catch (IOException i) {
            i.printStackTrace();
            return;
        } catch (ClassNotFoundException c) {
            System.out.println("MyClass not found");
            c.printStackTrace();
            return;
        }

        myClass.myMethod();
    }
}
Java

In this code, we’re deserializing the object we serialized in the previous example. We then call myMethod() on the deserialized object.

Transient Keyword and Its Role in Serialization

Sometimes, you might not want to serialize every field of an object. That’s where the transient keyword comes in. Any field marked as transient won’t be serialized. It’s like a VIP pass that lets a field skip the serialization party.

public class MyClass implements java.io.Serializable {
    private transient int myField;
    // rest of the class
}
Java

In this code, myField won’t be serialized because it’s marked as transient.

Java Serialization with Inheritance

When a superclass implements Serializable, its subclass does too. That means if you serialize an object of the subclass, the fields of the superclass will be included. But remember, if the superclass has fields marked as transient, those won’t be serialized.

Serialization and Its Impact on Java Constructors

During deserialization, the JVM doesn’t use any constructor to create the object. Instead, it creates the object directly from the serialized data. That means if your class has any code in its constructor, that code won’t be executed during deserialization.

Code Examples

Let’s put everything together with some complete code examples.

Code Example 1: A Simple Serialization and Deserialization Process

In this example, we will create a simple class Student with some fields. We will then serialize an object of this class and then deserialize it.

import java.io.*;

class Student implements Serializable {
    String name;
    int roll;

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

public class SerializeExample {
    public static void main(String[] args) {
        Student s1 = new Student("John", 101);

        try {
            FileOutputStream fileOut = new FileOutputStream("student.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(s1);
            out.close();
            fileOut.close();
            System.out.println("Serialized data is saved in student.ser");
        } catch (IOException i) {
            i.printStackTrace();
        }
    }
}
Java

In the above code, we have created a Student object s1 and serialized it. The serialized object is saved in a file named student.ser.

Now, let’s deserialize the student.ser file.

import java.io.*;

class Student implements Serializable {
    String name;
    int roll;

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

public class DeserializeExample {
    public static void main(String[] args) {
        Student s1 = null;

        try {
            FileInputStream fileIn = new FileInputStream("student.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            s1 = (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: " + s1.name);
        System.out.println("Roll: " + s1.roll);
    }
}
Java

In the above code, we have deserialized the student.ser file and printed the data of the Student object.

Code Example 2: Serialization with transient Keyword

In this example, we will see the use of transient keyword. We will create a class Employee with some fields where the ssn field is marked as transient.

import java.io.*;

class Employee implements Serializable {
    String name;
    transient int ssn;
    double salary;

    public Employee(String name, int ssn, double salary) {
        this.name = name;
        this.ssn = ssn;
        this.salary = salary;
    }
}

public class SerializeExample {
    public static void main(String[] args) {
        Employee e1 = new Employee("John", 123456789, 50000);

        try {
            FileOutputStream fileOut = new FileOutputStream("employee.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(e1);
            out.close();
            fileOut.close();
            System.out.println("Serialized data is saved in employee.ser");
        } catch (IOException i) {
            i.printStackTrace();
        }
    }
}
Java

In the above code, we have created an Employee object e1 and serialized it. The serialized object is saved in a file named employee.ser.

Now, let’s deserialize the employee.ser file.

import java.io.*;

class Employee implements Serializable {
    String name;
    transient int ssn;
    double salary;

    public Employee(String name, int ssn, double salary) {
        this.name = name;
        this.ssn = ssn;
        this.salary = salary;
    }
}

public class DeserializeExample {
    public static void main(String[] args) {
        Employee e1 = null;

        try {
            FileInputStream fileIn = new FileInputStream("employee.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            e1 = (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: " + e1.name);
        System.out.println("SSN: " + e1.ssn);
        System.out.println("Salary: " + e1.salary);
    }
}
Java

In the above code, we have deserialized the employee.ser file and printed the data of the Employee object. You will notice that the ssn field is not printed because it was marked as transient and hence was not serialized.

Frequently Asked Questions (FAQ)

  • What is Java serialization for?

    Java serialization is used to convert an object’s state into a byte stream, which can then be persisted to a disk or sent over a network. Later, this byte stream can be used to create a copy of the object in memory.

  • What is Serialisation vs deserialization Java?

    Serialization is the process of converting an object into a byte stream, while deserialization is the reverse process of creating an object from a byte stream.

  • Which is the API to do serialization in Java?

    The java.io.Serializable interface is used to mark a class as serializable. The java.io.ObjectOutputStream and java.io.ObjectInputStream classes provide methods for serializing and deserializing an object.

  • What is the real time use of serialization in Java?

    Serialization is used in situations where you need to send an object’s state over a network or save it to a file for later use. It’s commonly used in Remote Method Invocation (RMI), Java Management Extensions (JMX), Java Messaging Service (JMS), and JavaServer Faces (JSF) web applications.

  • What happens if a superclass is serializable but a subclass is not?

    If a superclass is serializable, its subclass is also implicitly serializable, even if it doesn’t explicitly implement the Serializable interface.

  • Why is the transient keyword used in Java?

    The transient keyword in Java is used to indicate that a field should not be serialized. This is useful when you want to hide sensitive data or when a field is derived from other fields.

  • What is the purpose of the Serializable interface?

    The Serializable interface is a marker interface that indicates the JVM can serialize the class. This interface doesn’t contain any methods.

  • What is the role of constructors in serialization?

    During deserialization, the JVM doesn’t use any constructor to create the object. Instead, it creates the object directly from the serialized data.

  • What is the serialVersionUID field in Java serialization?

    The serialVersionUID field is used to check the compatibility of classes during deserialization. If the serialVersionUID of the serialized class doesn’t match the serialVersionUID of the class in the JVM, a InvalidClassException is thrown.

  • Can we serialize static variables in Java?

    No, we cannot serialize static variables in Java. Static variables belong to the class, not to the object. Therefore, they are not part of the state of the object.

Conclusion

Java Serialization is a powerful feature that allows you to convert an object’s state into a byte stream, which can then be reverted back into a copy of the object. It plays a crucial role in storing object states in files or databases and in sending objects over a network. However, it’s important to use it wisely, as not all data should be serialized.

  1. Java Deserialization
  2. Understanding Java I/O Streams
  3. Java Networking Programming
  4. Java Remote Method Invocation (RMI)
Scroll to Top