What is the concept of Serialization in Java?

Last updated on Jun 17,2021 25.9K Views
Tech Enthusiast working as a Research Analyst at Edureka. Curious about learning... Tech Enthusiast working as a Research Analyst at Edureka. Curious about learning more about Data Science and Big-Data Hadoop.

What is the concept of Serialization in Java?

edureka.co

Serialization in Java is an important concept that deals with the conversion of objects into a byte stream to transport the java objects from one Java Virtual Machine to the other and recreate them to the original form. I will line up the docket for this article as below:

 

What is Serialization in Java?

Serialization in Java is the process of converting the Java code Object into a Byte Stream, to transfer the Object Code from one Java Virtual machine to another and recreate it using the process of Deserialization.

 

 

 

Why do we need Serialization in Java?

We need Serialization for the following reasons:

 

 

 

How do we Serialize an Object?

Java object is serializable if and only if its class or any of its parent classes implement either the java.io.Serializable interface or its subinterface, java.io.Externalizable.

In the Serialization process, we convert an object’s state into a byte stream so that it could be transferred from one JVM to the other and revert the byte stream back into the original object.

//Interface

package Serial1;

import java.io.Serializable;
public class Employee implements Serializable{
       private static final long serialVersionUID = 1L; //Serial Version UID
       int id;
       String name;
       public Employee(int id, String name) {
             this.id = id;
             this.name = name; 
       }
}

//Serialize

package Serial1;

import java.io.*;
class Persist{
       public static void main(String args[]){
               try{
                      Employee emp1 =new Employee(20110,"John");
                      Employee emp2 =new Employee(22110,"Jerry");
                      Employee emp3 =new Employee(20120,"Sam");
                      FileOutputStream fout=new FileOutputStream("output.txt");
                      ObjectOutputStream out=new ObjectOutputStream(fout);
                      out.writeObject(emp1);
                      out.writeObject(emp2);
                      out.writeObject(emp3);
                      out.flush();
                      out.close();
                      System.out.println("Serialization and Deserialization is been successfully executed");
               }
               catch(Exception e){
                      System.out.println(e);}
               }
}

Output:

Serialization and Deserialization is been successfully executed

Deserialization: It is the reverse process of Serialization where the Serialized Byte Stream of an object from the sender is recreated at the receiving end.

//Deserialise

package Serial1;

import java.io.*;
class Depersist{
      public static void main(String args[]){
            try{
                  ObjectInputStream in=new ObjectInputStream(new FileInputStream("output.txt"));
                  Employee e1=(Employee)in.readObject();
                  Employee e2=(Employee)in.readObject();
                  Employee e3=(Employee)in.readObject();
                  System.out.println(e1.id+" "+e1.name);
                  System.out.println(e2.id+" "+e2.name);
                  System.out.println(e3.id+" "+e3.name);
                  in.close();
            }
            catch(Exception e){
                  System.out.println(e);}
            }
}

Output:

20110 John
22110 Jerry

20120 Sam

 

Advantages and Disadvantages of Serialization in Java

Advantages:

 

 

Disadvantages:

 

 

 

Practical examples of Serialization in Java

 

Serialization Using Inheritance

Case – 1: If Superclass is Serializable, then, by default, its Subclasses are also serializable. 

In this case, the subclass is serializable by default if the superclass is implementing the Serializable Interface

package SerializationInheritance;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class A implements Serializable{
        int i;
        public A(int i){
                this.i = i;
        }
}
class B extends A{
         int j;
         public B(int i, int j){
                super(i);
                this.j = j;
         }
}
public class Test{
          public static void main(String[] args)throws Exception{
                  B b1 = new B(200,400);
                  System.out.println("i = " + b1.i);
                  System.out.println("j = " + b1.j);
                  FileOutputStream fos = new FileOutputStream("abc.ser");
                  ObjectOutputStream oos = new ObjectOutputStream(fos);
                  oos.writeObject(b1);
                  oos.close();
                  fos.close();
                  System.out.println("The object has been serialized");
                  FileInputStream fis = new FileInputStream("abc.ser");
                  ObjectInputStream ois = new ObjectInputStream(fis);
                  B b2 = (B)ois.readObject();
                  ois.close();
                  fis.close();
                  System.out.println("The object has been deserialized");
                  System.out.println("i = " + b2.i);
                  System.out.println("j = " + b2.j);
          }
}

Output:

j = 20
The object has been serialized
The object has been deserialized
i = 200
j = 400

Case – 2: A Subclass can be serialized if it implements the Serializable Interface even if a Superclass does not implement the Serializable Interface.

In this case, if the superclass is not implementing the Serializable Interface, then, the objects of the subclass can be manually serialized by implementing the Serializable Interface in the subclass.


package SerializationInheritance;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;;

class superclass {
      int i;
      public superclass(int i) {
           this.i = i;
      }
      public superclass() {
           i = 50;
           System.out.println("Superclass constructor called");
     }
}
class subclass extends superclass implements Serializable {
      int j;
      public subclass(int i, int j) {
            super(i);
            this.j = j;
      }
}
public class test2 {
      public static void main(String[] args) throws Exception {
            subclass b1 = new subclass(10, 20);
            System.out.println("i = " + b1.i);
            System.out.println("j = " + b1.j);
            FileOutputStream fos = new FileOutputStream("output.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(b1);
            oos.close();
            fos.close();
            System.out.println("The object has been serialized");
            FileInputStream fis = new FileInputStream("output.ser");
            ObjectInputStream ois = new ObjectInputStream(fis);
            subclass b2 = (subclass) ois.readObject();
            ois.close();
            fis.close();
            System.out.println("The object has been deserialized");
            System.out.println("i = " + b2.i);
            System.out.println("j = " + b2.j);
      }
}

The object has been serialized
Superclass constructor called
The object has been deserialized
i = 50
j = 20

Case – 3: If the superclass is serializable, but we do not need the subclass to be serialized.

In this case, the Serialization of the subclass can be prevented by implementing the writeObject()and readObject() methods in the subclass and it needs to throw NotSerializableException from these methods.

package SerializationInheritance;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Parent implements Serializable {
       int i;
       public Parent(int i) {
             this.i = i;
       }
}

class child extends Parent {
        int j;
        public child(int i, int j) {
               super(i);
               this.j = j;
        }
        private void writeObject(ObjectOutputStream out) throws IOException {
               throw new NotSerializableException();
        }
        private void readObject(ObjectInputStream in) throws IOException {
               throw new NotSerializableException();
        }
}

public class test3 {
        public static void main(String[] args) throws Exception {
               child b1 = new child(100, 200);
               System.out.println("i = " + b1.i);
               System.out.println("j = " + b1.j);
               FileOutputStream fos = new FileOutputStream("abc.ser");
               ObjectOutputStream oos = new ObjectOutputStream(fos);
               oos.writeObject(b1);
               oos.close();
               fos.close();
               System.out.println("Object has been serialized");
               FileInputStream fis = new FileInputStream("abc.ser");
               ObjectInputStream ois = new ObjectInputStream(fis);
               child b2 = (child) ois.readObject();
               ois.close();
               fis.close();
               System.out.println("Object has been deserialized");
               System.out.println("i = " + b2.i);
               System.out.println("j = " + b2.j);
       }
}

Output:

i = 100
j = 200
Exception in thread "main" java.io.NotSerializableException
at SerializationInheritance.child.writeObject(test3.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

 

Serialization Using a Static Member

Serialization of static member field is ignored in the process of serialization. Serialization is related to the object’s latest state. Hence, only the data associated with a specific instance of a class is serialized but not the Static member field.

package stati;
import java.io.*;
class StaticSerial implements Serializable{
      static int i =100; 
      public static void main(String... ar){
      StaticSerial ob= new StaticSerial();
      System.out.println("At the time of Serialization, static member has value : " + i);
      try{
             FileOutputStream fos= new FileOutputStream("F:File.ser"); 
             ObjectOutputStream oos= new ObjectOutputStream(fos);
             oos.writeObject(ob); 
             oos.close();
             i=99; 
             FileInputStream fis= new FileInputStream("F:File.ser"); 
             ObjectInputStream ois= new ObjectInputStream(fis);
             ob=(StaticSerial)ois.readObject();
             ois.close();
             System.out.println("After Deserialization, static member has value : "+ i);
      }
      catch(Exception e){
            System.out.println(e);
      }
   }
}

Output:

At the time of Serialization, static member has value : 100
After Deserialization, static member has value : 99

 

Externalizable Interface

The Externalizable Interface in Java is similar to Serialization but the only difference is that it is capable to offer customized serialization where you get to decide the objects to be sored in the stream.

The Externalizable interface is available in the java.io and it provides two methods:

The Key differences between Serialization and Externalizeable are as follows:

 

 

Whereas, Serializable Interface does not include any methods.

 

package ext;
import java.io.*;
class Demo implements java.io.Serializable{
      public int a;
      public String b;
      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, "Welcome to Edureka");
           String filename = "file.ser";
           try{
                  FileOutputStream file = new FileOutputStream(filename);
                  ObjectOutputStream out = new ObjectOutputStream(file);
                  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;
           try{
                  FileInputStream file = new FileInputStream(filename);
                  ObjectInputStream in = new ObjectInputStream(file);
                  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");
           }
      }
}

 

 

Transient Keyword

Transient Keyword is a reserved keyword in Java. It is used as a variable modifier at the time of the Serialization process. Declaring a variable with Transient keyword avoids the variable from being Serialized.

 

Serial Version UID

Before the process of serialization begins, every serializable class/object gets associated with a unique identification number provided by the JVM of the host machine. This Unique ID is called Serial Version UID. This UID is used as an identification by the JVM of the receiving end to confirm that the same object is being DeSerialized at the receiving end.

 

Controversies of Serialization in Java

Oracle’s Architects intend to remove Serialization from Java as they consider it as a Horrible Mistake of 1997. After hectic research, the developers at Oracle found out a few flaws in the design of Serialization procedure which pose a threat to the data.

In the year 1997, Mark Reinhold states – “We like to call serialization ‘the gift that keeps on giving,’ and the type of gift it keeps on giving is security vulnerabilities. Probably a third of all Java vulnerabilities have involved serialization; it could be over half. It is an astonishingly fecund source of vulnerabilities, not to mention instabilities.”.

There are chances that Serialization would be removed or replaced in the upcoming updates of Java and on the other hand, for a beginner in Java, Serialization could not be an idealistic option in their projects

 

Best Practices while using Serialization in Java

The following are a few best practices that need to be followed

With this, we have come to the end of this article. I hope you have understood the basics of Serialization in Java, its types and its functionalities.

Check out the Java Certification Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Mention it in the comments section of this “Serialization in Java” article and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 21st December,2024

21st December

SAT&SUN (Weekend Batch)
View Details
Java Course Online

Class Starts on 1st March,2025

1st March

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Building Robust Applications with Spring Framework