Serializable Interface in Java


The Serializable interface provides the facility to serialize an object. It does not define any methods and member variables. When a class implements serializable interface it simply indicates this class and its sub-classes can be serialized. The serializable interface serves to achieve the Serialization and Deserialization of an object.

In this article, we will discuss the use of Serializable Interface in Java with examples.

Serialization and Deserialization in Java

Serialization is a mechanism used to represent a given object into a sequence of bytes and its opposite is deserialization which represents a sequence of bytes into an object. Other than static and transient variables, all members of a class can be preserved during the serialization process. These operations have many applications one of them is Remote Method Invocation which allows the invocation of a method from one machine to another.

As we have discussed earlier the only way to use serialization facility is by using the serializable interface. Therefore, we need to implement it first.

Syntax for Serializable Interface

accesSpecifier class nameOfclass implements Serializable {
   // your code here
}  

accesSpecifier − It is used to set the accessibility of the method. It may be public, protected, default and private.

implements − It is a keyword that enables the use of functionality of an interface to the class associated with it.

To work with serializable interface, it is important to import the following package −

import java.io.*;

Here, * signifies that we are importing all the classes as well as methods available in this package into our program.

Before jumping into the example of serializable interface, it is necessary to discuss a few more things.

ObjectOutputStream

It is a sub class of OutputStream class and implements ObjectOutput interface. It contains a variety of methods and writeObject is one of them that takes an object as an argument and converts it to a sequence of bytes means it serializes the given object. Only the object of those classes can be passed as an argument that implements Serializable interface.

Syntax

writeObject(nameOfobject);

ObjectInputStream

It is a sub class of InputStream class and implements ObjectInput interface. It contains various methods and readObject is one of them that converts the byte stream back to the object means it performs deserialization.

Syntax

readObject();

Example 1

In the following example, we will understand the implementation of serializable interface.

Algorithm

  • Step 1 − We will begin with defining a class named ‘Details’ that implements Serializable interface. In this class, declare two instance variables ‘st’ and ‘id’. This information will be going to serialized and deserialized later.

  • Step 2 − In the main method, define a try block. Inside this block, create an object named ‘strmOut’ of ObjectOutputStream class for the file stream of FileOutputStream. Here, FileOutputStream refers to file name ‘stream’. Then using ‘writeObject’ method we will serialize the ‘obj1’ of class ‘Details’.

  • Step 3 − Inside the next try block, we will create an object named ‘strmIn’ of ObjectInputStream class for the file stream of FileInputStream. Here, FileInputStream refers to file name ‘stream’. Then using ‘readObject’ method we will deserialize the object and print the result.

  • Step 4 − The catch block of corresponding try blocks will handle if any kind of exception occurs during the whole process.

import java.io.*;
class Details implements Serializable {
   String st;
   int id;
   public Details(String st, int id) {  
      // constructor
      this.st = st;
      this.id = id;
   }
   // method for converting object into string
   public String toString() { 
      return "st = " + st + ", id = " + id;
   }
}
public class SerialDemo {
   public static void main(String args[]) {
      // code for serialization of object
      try {
         // creating object of ObjectOutputStream
         ObjectOutputStream strmOut =
         new ObjectOutputStream(new FileOutputStream("stream"));
         // passing data to object 1
         Details obj1 = new Details("Tutorial 1", 121);
         System.out.println("Data of object 1 is passed to object2....");
         strmOut.writeObject(obj1);
      }
      catch(IOException exp) {
         System.out.println("Exception occurred during serialization of Object 1: " + exp);
      }
      // code for deserialization of object
      try {
         // creating object of ObjectInputStream
         ObjectInputStream strmIn = new ObjectInputStream(new FileInputStream("stream"));
         // reading the details of object 1
         Details obj2 = (Details)strmIn.readObject();
         System.out.println("Data of object 2: " + obj2);
      }
      catch(Exception exp) {
         System.out.println("Exception occurred during deserialization of Object 2: " + exp);
      }
   }
}

Output

Data of object 1 is passed to object2....
Data of object 2: st = Tutorial 1, id = 121

Conclusion

The only use case of serializable interface is the serialization and deserialization of an object. We can store text, audio, or any custom data in a serialized object. In this article, we have listed out all the methods that help us in this process.

Updated on: 12-May-2023

768 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements