Friday 8 December 2017

What is Serialization in Java and Give an Example?


  1. It is a process of converting the state of an object into a byte stream
  2. A class must implement Serializable interface present in java.io package in order to serialize its object
  3. Serializable is the example of Marker Interface
  4. It is used in Hibernate,RMI, JPA, EJB and JMS..

 Advantages of Serialization
  1.  To save/persist state of an object.
  2.  To move  an object across a network.

Points to remember
  1. If a parent class has implemented Serializable interface then child class doesn’t need   to  implement it (Imp point).
  2.  Only non-static data members are used in Serialization process.
  3.  Static data members are not saved in Serialization.
  4.  Constructor of object is never called when an object is deserialized.


Example:
import java.io.*;
public class Employee implements Serializable
{
    String name;
    int EmpId;
    static String company;
Employee (String nm, int Ed, String c)
    {
    this.name = nm;
    this.EmpId =Ed;
    this.contact = c;
    }
}

class Test
{
    public static void main(String[] args)
    {
        try
        {
     Employee emp = new Employee ("Dipak", 105, "LearingPoint92");
            FileOutputStream fos = new FileOutputStream("emp.txt");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(emp);
            oos.close();
            fos.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Explanation:

Object of Employee class is serialized using  writeObject() method and written to emp.txt file.

Deserialization

The reverse operation of serialization is called deserialization.

Converting   byte stream into the state of an object is called deserialization

import java.io.* ;

public class DeserializationDemo
{
public static void main(String[] args)
    {
Employee emp=null;
        try
        {
            
            FileOutputStream fos = new FileOutputStream("emp.txt");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            emp=(Employee)oos.readObject();
         }

catch (Exception e)
        {
         e.printStackTrace();
            System.out.println(emp.name);
            System.out. println(emp.EmpId);

            System.out.println(emp.company);
        }
}

Output:
Dipak
105
null

Company field is null because, it was declared as static and as we have pointed 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

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...