Serialization and Deserialization in Java

1. Java SerDe – Objective

In our last tutorial, we discussed Java Packages tutorial. Here, in this tutorial for Java, we are going to study the process of Java serialization and deserialization in Java, Serialization in java real-time examples, Deserialization in java with examples, and advantages and disadvantages of Serialization in Java and Deserialization in Java.

So, let us start with Serialization and Deserialization in Java.

2. What is Serialization and Deserialization in Java?

The process of serialization in Java is a process in which the object’s state is converted into a byte stream while deserialization is just the reverse of serialization in which we use the byte stream to convert into the original state of a Java object.

Do you know about What is Encapsulation in Java?

The classes which serialized should have the implementation java.io.Serializable interface. Serializable in Java is used to mark classes, so that they may get the certain capability, it is basically a marker interface.

Points to ponder

i. If serializable implement in a certain parent class then we don’t need to implement it in the child class, but the reverse is not applicable.

ii. Nonstatic data members are stored via this method and not static and transient data members.

iii. A constructor for an object is never called while deserialization.

Follow this link to know about java.io.File Class in Java

Example –

class A implements Serializable
{
// B also implements Serializable interface.
B ob=new B();
}

3. SerialVersionUID

A serializable class associates itself with a SerialVersionUID while the Java serialization runtime. This use during Java Deserialization to verify that the object load by the sender and receiver of a serialized object is compatible with respect to Java serialization if the UID is different it will result in InvalidClassException. A class which can serialize can declare its own UID by declaring a field name which should be of type long, static and final. If it doesn’t explicitly declare a seialVersionUID then a default one will automatically create by runtime based on various aspects of class as described by the Java Object Serialization Specification. It recommends to specify UID as any change in information can highly change the results and also to declare it as private so it not inherit.

Read about Inheritance in Java

Serialver – This tool is to get serialVersionUID of Java classes, it comes with JDK.

Java Quiz

4. Advantages and Disadvantages

Following are the Advantages and Disadvantages of Deserialization and Serialization in Java.

i. Serialization is very easy to use and also a serialized stream supports secure Java computing as it can authenticate, encrypt and compress. It supports coherent versioning and also supports flexible to allow the gradual evolution of the program. It can also used to support exchange in libraries between Java and C++.

ii. The disadvantages being, it cannot be used with large sized objects, also It offers overheads, this in whole delays the process of garbage collection as large objects contain large memory.

5. Examples of Serialization and Deserialization in Java

a. Example 1

// 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 Test
   {
      public static void main(String[] args)
          {
              Demo object = new Demo(1, "geeksforgeeks");
              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");
     }
   }
}

Read about Java Garbage Collection Algorithm in detail

b. Example 2

// Java code for serialization and deserialization of a Java object
import java.io.*;
class Emp implements Serializable
     {
          private static final long serialversionUID =
          129348938L;
          transient int a;
          static int b;
          String name;
          int age;
// Default constructor
public Emp(String name, int age, int a, int b)
         {
              this.name = name;
              this.age = age;
              this.a = a;
              this.b = b;
         }
    }
public class SerialExample
          {
              public static void printdata(Emp object1)
                    {
                       System.out.println("name = " + object1.name);
                       System.out.println("age = " + object1.age);
                       System.out.println("a = " + object1.a);
                       System.out.println("b = " + object1.b);
                    }
public static void main(String[] args)
         {
              Emp object = new Emp("ab", 20, 2, 1000);
              String filename = "shubham.txt";
// 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\n"
                    + "Data before Deserialization.");
                    printdata(object);
// value of static variable changed
                    object.b = 2000;
                 }
      catch (IOException ex)
          {
                System.out.println("IOException is caught");
          }
     object = null;
// Deserialization
     try
{
// Reading the object from a file
     FileInputStream file = new FileInputStream
     (filename);
     ObjectInputStream in = new ObjectInputStream
     (file);
// Method for deserialization of object
     object = (Emp)in.readObject();
     in.close();
     file.close();
     System.out.println("Object has been deserialized\n"
     + "Data after Deserialization.");
     printdata(object);
// System.out.println("z = " + object1.z);
}
catch (IOException ex)
    {
         System.out.println("IOException is caught");
    }
catch (ClassNotFoundException ex)
       {
           System.out.println("ClassNotFoundException" +
           " is caught");
       }
   }
}

6. Conclusion

In this serialization and deserialization in Java tutorial, we learned what is serialization in Java and what is deserialization in Java. Java serialization with examples Program and Java serialization with example Program some other features of serialization and deserialization in Java.

See Also- Abstraction in Java & Decision Making in Java

For reference

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.