Categories: Java

Serialization and Deserialization in Java

An object’s state can be transformed into a byte stream through a process known as serialization. Deserialization is the opposite procedure, in which the actual Java object is recreated in memory using a byte stream. This mechanism is used to persist the object.

We use the writeObject() function of the ObjectOutputStream class to serialize the object, and the readObject() method of the ObjectInputStream class to deserialize it.

Characteristics of Serialization:
  • To maintain an object’s state.
  • To travel an object across a network.

For the purpose of serializing and deserializing objects, Java offers Serializable API, which is contained within the java.io package.

  • java.io.serializable
  • java.io.
  • Externalizable
  • ObjectInputStream
  • ObjectOutputStream
Java Marker interface:

A marker interface is called serializable (has no data member and method). Java classes are “marked” with this technique in order for their objects to gain specific capabilities. Cloneable and Remote interfaces for markers are other examples.

Some examples of Marker interface are:

  • java.io.serializable
  • java.lang.Cloneable
  • java.rmi.Remote
  • java.util.RandomAccess
ObjectOutputStream class:

Java objects and primitive data types can be written to an output stream using the ObjectOutputStream class. Only objects that support the java.io.Serializable interface can be written to streams.

Constructor:

public ObjectOutputStream(OutputStream out) throws IOException {}

Methods:

  • public final void writeObject(Object obj) throws IOException {}
  • public void flush() throws IOException {}
  • public void close() throws IOException {}
ObjectInputStream class:

Objects and primitive data written using an ObjectOutputStream are deserialized by an ObjectInputStream.

Constructor:

public ObjectInputStream(InputStream in) throws IOException {}

Methods:

  • public final Object readObject() throws IOException, ClassNotFoundException{}
  • public void close() throws IOException {}
Example
// Java code for serialization and deserialization
// of a Java object
import java.io.*;

class Demo implements java.io.Serializable
{
 public int a;
 public String b;

 // Default constructor
 public Demo(int a, String b)
 {
  this.a = a;
  this.b = b;
 }

}

class Coderz
{
 public static void main(String[] args)
 {
 Demo object = new Demo(1, "Coderz");
  String filename = "file.ser";
  
  // Serialization
  try
  {
   //Saving of object in a file
   FileOutputStream file = new FileOutputStream(filename);
   ObjectOutputStream out = new ObjectOutputStream(file);
   
   // Method for serialization of object
   out.writeObject(object);
   
   out.close();
   file.close();
   
   System.out.println("Object has been serialized");

  }
  
  catch(IOException ex)
  {
   System.out.println("IOException is caught");
  }


Demo object1 = null;

  // Deserialization
  try
  {
   // Reading the object from a file
   FileInputStream file = new FileInputStream(filename);
   ObjectInputStream in = new ObjectInputStream(file);
   
   // Method for deserialization of object
   object1 = (Demo)in.readObject();
   
   in.close();
   file.close();
   
   System.out.println("Object has been deserialized ");
   System.out.println("a = " + object1.a);
   System.out.println("b = " + object1.b);
  }
  
  catch(IOException ex)
  {
   System.out.println("IOException is caught");
  }
  
  catch(ClassNotFoundException ex)
  {
   System.out.println("ClassNotFoundException is caught");
  }

 }
}
Output
Object has been serialized
Object has been deserialized 
a = 1
b = Coderz

Note: also read about the Input-output Stream in Java

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

3 hours ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

2 days ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

4 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago