Thursday 4 February 2016

SERIALIZATION AND DESERIALIZATION IN JAVA

Serialization is a process of converting an object into a sequence of bytes which can be persisted to a disk or database or can be sent through streams. The reverse process of creating object from sequence of bytes is called deserialization.
A class must implement Serializable interface present in java.io package in order to serialize its object successfully. Serializable is a marker interface that adds serializable behaviour to the class implementing it.
Java provides Serializable API encapsulated under java.io package for serializing and deserializing objects which include,
  • java.io.serializable
  • java.io.Externalizable
  • ObjectInputStream
  • and ObjectOutputStream etc.
serialization and deserialization of objects
Serializing an object:
import java.io.*;
class studentinfo implements Serializable 
{
 String name;
 int rid;
 static String contact;
 studentinfo(string n, int r, string c)
 {
  this.name = n;
  this.rid = r;
  this.contact = c;
 }
}

class Test
{
 public static void main(String[] args)
 {
 try
 {
  Studentinfo si = new studentinfo("Abhi", 104, "110044");
  FileOutputStream fos = new FileOutputStream("student.ser");
  Objectoutputstream oos = new ObjectOutputStream(fos);
  oos.writeObject(si);
  oos.close();
  fos.close();
  }
  catch (Exception e)
  { e. printStackTrace(); }
 }
}
Object of Studentinfo class is serialized using writeObject() method and written to student.ser file.
Deserialization of Object:
import java.io * ;
class DeserializationTest
{
 public static void main(String[] args)
 {
  studentinfo si=null ;
  try  
  {
   FileInputStream fis = new FileInputStream("student.ser");
   ObjectOutputStream ois = new ObjectOutputStream(fis);
   si = (studentinfo)ois.readObject();
  } 
  catch (Exception e)
   { e.printStackTrace(); }
  System.out.println(si.name);
  System.out. println(si.rid);
  System.out.println(si.contact);
 }
}
Output :
Abhi
104
null
Contact field is null because,it was marked as static and as we have discussed earlier static 
fields does not get serialized.
NOTE : Static members are never serialized because they are connected to class not object of class.

No comments:

Post a Comment