Serialization in java

Serialization in Java

The process in java where an object is converted in the form of bytes to store it in the memory, in a file or in any database is called serialization. We need to do serialization in order to recreate the object, whenever required by us. we sometimes need to change the state of an object because if JVM faces any issue, the object is automatically affected by it. Java objects are most probably not understand. whereas bytes are easy to understand. This process is done to retain the basic state of an object.

The byte stream that is created out of an object is platform-independent. Hence, it is not always compulsory to serialize and de-serialize the object on the same platform. The bytes can be again transformed into a live object later.  The revoking back of the process of serialization is called de-serialization.

The main advantages of serialising an object are:

  • To move an object across the data network.
  • To save the basic state of an object.
  • We can access the byte stream of the object in the database whenever we want, as it gets saved on the network.
  • It is very easy to understand and is customizable.
  • The serialized state can be revoked back.

How does serialization work in java?

To serialise an object, we implement java.io.Serializable interface and the method we use of this process is writeObject() available in ObjectOutputStream class. Similarly, for de-serializing an object, we require readObject() available in ObjectInputStream class.

  • ObjectOutputStream.writeObject(): this will write a serializable object to the output stream. The method throws an exception as NotSerializableException.  Serializable interface cannot be implemented by the object to be serialized.
  • ObjectInputStream.readObject(): this will read, construct and return an object from the input stream. The method will throw an exception as ClassNotFoundException if class of a serialized object cannot be found.

Below is a Simple Serialization Syntax for better understanding of the concept

class X implements Serializable{

// Y also implements Serializable
// interface.
Y ob=new Y();  
}

Here is a Simple program to execute Serialization and de-serialization:

import java.io.*; 
  
class Demo implements java.io.Serializable 
{ 
    public int x; 
    public String y; 
  
     
    public Demo(int a, String b)                       
// Default constructor
    { 
        this.x = x; 
        this.y = y; 
    } 
  
} 
class A
{ 
    public static void main(String[] args) 
    {    
        Demo object = new Demo(1, "developerhelps"); 
        String filename = "file.ser"; 
          
         
        try                                                               
// Performing Serialization 
        {    
             
            FileOutputStream file = new FileOutputStream(filename);       //Saving of object in a file
            ObjectOutputStream out = new ObjectOutputStream(file); 
              
             
            out.writeObject(object);                             
// Method for serialization of object
              
            out.close(); 
            file.close(); 
              
            System.out.println("Object has been serialized"); 
  
        } 
          
        catch(IOException ex) 
        { 
            System.out.println("IOException is caught"); 
        } 
  
  
        Demo objectnew = null; 

  try   
                                                                //Deserialization
        {    
             
            FileInputStream file = new FileInputStream(filename);           // Reading the object from a file
            ObjectInputStream in = new ObjectInputStream(file); 
              
             
            objectnew = (Demo)in.readObject();   

// Method for deserialization of object
              
            in.close(); 
            file.close(); 
              
            System.out.println("Object has been deserialized "); 
            System.out.println("x = " + objectnew.x); 
            System.out.println("y = " + objectnew.y); 
        } 
          
        catch(IOException ex) 
        { 
            System.out.println("IOException is caught"); 
        } 
          
        catch(ClassNotFoundException ex) 
        { 
            System.out.println("ClassNotFoundException is caught"); 
        } 
  
    } 
} 

             
            objectnew = (Demo)in.readObject();                                 // Method for deserialization of object
              
            in.close(); 
            file.close(); 
              
            System.out.println("Object has been deserialized "); 
            System.out.println("x = " + objectnew.x); 
            System.out.println("y = " + objectnew.y); 
        } 
          
        catch(IOException ex) 
        { 
            System.out.println("IOException is caught"); 
        } 
          
        catch(ClassNotFoundException ex) 
        { 
            System.out.println("ClassNotFoundException is caught"); 
        } 
  
    } 
} 

The output of the program will be:

Object has been deserialized
Object has been deserialized
a=1
b-= developerhelps

Important points to remember about Serialization:

  • If a parent class implements Serializable interface, then child class doesn’t require implementing it however it is not true for the opposite case.
  • We can only save non-static data members during the serialization process.
  • We cannot save static and transient data members via the serialization process. In case one doesn’t want to save a non-static data member, convert it to transient.
  • The constructor of object cannot be called if an object is not serialized.
  • The process of serialization is not dependent on any platform.
  •  The default process of serialization in java is recursive. It implies that if we try to serialize an object, Java will try to serialize the whole field.
  • none of the access specifiers such as ‘private’ work well for this process.

Leave a comment

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