articles

Home / DeveloperSection / Articles / Serialization in Java

Serialization in Java

Anupam Mishra4533 17-Nov-2015

It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies.

The main advantage of Serialization is to be travel object's state on the network (known as marshaling).

The reverse operation of serialization is called deserialization. Deserialization is the process of reconstructing the object from the serialized state.

The String class and all the wrapper classes’ implements java.io.Serializable interface by default.

Serializable is a marker interface (has no body). It is just used to "mark" java classes which support a certain capability. It must be implemented by the class whose object you want to persist.

Let’s take an example, we are going to serialize the object of Emp & MyClient class. The writeObject () method of ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the object in the file named Employee.txt. and deserialized in MyServer class.

Note:-
1.    Only non-static data member are saved via serialization process.
2.    Static data member and transient data member are not saved via serialization process.
3.    If you does not want to save the value of any non- static data member via serialization process then make it transient.
4.    If parent class has implemented the Serializable interface then child class does not need to implement but vice versa is not true. 

      import java.io.*;
//Emp.java
public class Emp  implements Serializable
{
transient int a;//it will not be serialized.
static int b;
String name;
int age;
int z;
Emp(String name,int age,int a,int b,int z)
{
    this.name=name;
    this.age=age;
    this.a=a;
    this.b=b;
    this.z=z;

}
class  MyClient
{
  public MyClient()
    {
        try{
            Emp e1= new Emp("Anupam Mishra",24,5,10,15);
            FileOutputStream fout=new FileOutputStream("Employee.txt");  
  ObjectOutputStream out=new ObjectOutputStream(fout);  
  
  out.writeObject(e1);  
            out.flush();
        }catch(Exception e){System.out.println(e);}
    }
    public static void main(String...ss)
    {new MyClient();
    System.out.println("Serialization in MyClient is success");}
}
class MyServer
{
    ObjectInputStream dis;
    public MyServer()
    {
        try{
            dis=new ObjectInputStream(new FileInputStream("Employee.txt"));
            Emp z= (Emp)dis.readObject();
            System.out.println("Name :"+z.name);
            System.out.println("Age :"+z.age);
            System.out.println("a :"+z.a);
            System.out.println("b :"+z.b);
            System.out.println("Z :"+z.z);
        }catch(Exception e){System.out.println(e);}
        }
        public static void main(String...ss)
    {new MyServer();
    System.out.println("Deserialized in MyServer is completed");}}
Output:


Serialization in Java

Updated 07-Sep-2019

Leave Comment

Comments

Liked By