Serialization and Deserialization

Serialization is one of the most important question in Java Interview . In this blog I have written detailed analysis about serialization and deserialization

Serialization :

  • Converting an object into Network oriented format

  • Writing an Object into a file

  • Saving an object into a file

Deserialization :

  • Converting an Object from Network Readable format or File Supported to Object format

  • Reading an Object from the file

In Serialization we will use ObjectOutputstream and FileOutputStream

In Deserialization we will use ObjectInputStream and FileInputStream

//Test class implements Serializable
class Test implements Serializable
{
  int i=10;
  int j=20;
}

class Serialization
{
   public static void main(String args[]){
       Test d1=new Test();

      //Serialization
      FileOutputStream fos=new FileOutputStream("abc.txt");
      ObjectOutputstream oos =new ObjectOutputstream(fos);
      oos.writeObject(d1);

      //Deserialization
      FileInputStream fis =new FileInputStream("abc.txt");
      ObjectInputStream ois =new ObjectInputStream(fis);
     Test d2=(Test)ois.readObject()

   }
}
  • if the Test class doesn't implement a serializable interface then we will get RE: NotSerializableException: Test
  • we can serialize only serializable objects. an object is said to be serializable if and only if the corresponding class implements the serializable interface. it is present in the java.io package and it doesn't contain any methods. hence it is a marker interface.
  • In serialization transient keyword play a very important role. is applicable only for variables not for methods and classes

  • if we don't want to pass sensitive information to a file make that Attribute as transient then JVM will ignore original value and it will write the default value to Achieve security transient keyword plays a major role

  • Transient means not to serializable .static variable won't participate in serialization there is no impact of making a variable transient static