Java/J2EE and SOA (348 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (345 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

What is the concept of Serialization in Java?

Last updated on Jun 17,2021 25.3K Views

Ravi Kiran
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.

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.

Serialization-in-Java-Edureka-Picture-1

 

 

 

Why do we need Serialization in Java?

We need Serialization for the following reasons:

  • Communication: Serialization involves the procedure of object serialization and transmission. This enables multiple computer systems to design, share and execute objects simultaneously.

  • Caching: The time consumed in building an object is more compared to the time required for de-serializing it. Serialization minimizes time consumption by caching the giant objects.

  • Deep Copy: Cloning process is made simple by using Serialization. An exact replica of an object is obtained by serializing the object to a byte array, and then de-serializing it.

  • Cross JVM Synchronization: The major advantage of Serialization is that it works across different JVMs that might be running on different architectures or Operating Systems

  • Persistence: The State of any object can be directly stored by applying Serialization on to it and stored in a database so that it can be retrieved later.

 

Serialization-in-Java-Edureka-Picture-2

 

 

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:

 

 

  • Serialization process is a built-in feature that does not require third-party software to execute Serialization
  • The Serialization procedure is proven to be simple and easy to understand

  • Serialization procedure is universal and developers from different background are familiar to it

  • It is easy to use and simple to customize

  • Serialized data streams support Encryption, Compression, Authentication and secure Java computing

  • There are many critical technologies relying on serialization.

Disadvantages:

 

 

  • Objects while DeSerialization becomes brittle and they are not sure to be DeSerialized effectively.

  • The Transient variables declared while Serialization creates memory space, but the constructor is not called which results in the failure in the initialization of transient variables resulting in a variation to the Standard Java Flow.

  • The process of serialization is inefficient in terms of memory utilization.

  • Serialization is not preferable to be used in the applications which need concurrent access without the requirement of third-party APIs, as Serialization does not offer any transition control mechanism per every SE.

  • Serialization procedure fails to offer fine-grained control to access Objects.

 

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:

  • public void writeExternal(ObjectOutput out) throws IOException
  • public void readExternal(ObjectInput in) throws IOException

The Key differences between Serialization and Externalizeable are as follows:

 

Serialization-in-Java-Edureka-Picture-3

 

  • Implementation: Externalizable Interface excepts the user to explicitly mention the objects to be serialized. While in Serialization Interface, all the objects and variables are serialized in the run-time.

implement-serailzation

  • Methods: Externalizable interface consists of two methods, namely:

    • writeExternal()

    • readExternal()

Whereas, Serializable Interface does not include any methods.

process

  • Process: Serialization process in Externalizable Interface provides customization to the serialization process. But, Serialization Interface will provide the default serialization process.

method

  • Backwards Compatability and Control: Externalizable Interface supports Serialization regardless of the version control and the only problem is that the user must be responsible while serializing Super Class. On the other hand, Serialization Interface requires the same version of JVMs on both the ends but it incorporates automatic serialization of all the objects and classes including the superclass.

backward compatability and control

  • Public No-Arg Constructor: Externalization Interface needs Public No-Arg Constructor to reconstruct the serialized object. While Serialization Interface does not require No-Arg Constructor, instead it uses reflection to reconstruct the serialized object or class.

constructor

 

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

  • It is recommended use javadoc@serial tag for denoting Serializable fields.
  • The .ser extension is preferred to be used for files representing serialized objects.
  • It is not recommended for any static or transient fields to undergo default serialization.
  • Extendable classes should not be Serialized unless it is mandatory.
  • Inner Classes should be avoided to be involved in Serialization.

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 Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 27th April,2024

27th April

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 18th May,2024

18th May

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What is the concept of Serialization in Java?

edureka.co