Serialization in Java

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 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.

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. 

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)

class  MyClient
  public MyClient()
            Emp e1= new Emp('Anupam Mishra',24,5,10,15);
            FileOutputStream fout=new FileOutputStream('Employee.txt');  
  ObjectOutputStream out=new ObjectOutputStream(fout);  
        }catch(Exception e){System.out.println(e);}
    public static void main(
    {new MyClient();
    System.out.println('Serialization in MyClient is success');}
class MyServer
    ObjectInputStream dis;
    public MyServer()
            dis=new ObjectInputStream(new FileInputStream('Employee.txt'));
            Emp z= (Emp)dis.readObject();
            System.out.println('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(
    {new MyServer();
    System.out.println('Deserialized in MyServer is completed');}}

Serialization in Java
Last updated:9/7/2019 12:16:01 AM


Leave Comment