Serialization in Java Example

Serialization is a process through which Objects can be converted into streams, the reverse process is termed as De-Serialization. The functionality of serialization and deserialization can be achieved with the help of Serializable interface which is present inside java.io package.

It is a marker interface. A marker interface is a blank interface which it does not contain any declaration whatsoever.

1. Write: Program - SerialWrite.java

import java.io.*;

class A implements Serializable{
    int a, b;
    A(int a, int b){
        this.a=a;
        this.b=b;
    }
    
    void display(){
        System.out.println("a="+a+" : b="+b);
    }

}


class Serial{
    public static void main(String[] args) throws IOException{
        FileOutputStream fos=new FileOutputStream("details.txt");
        ObjectOutputStream oos=new ObjectOutputStream(fos);
        A obj=new A(5, 10);
        oos.writeObject(obj);
        oos.close();
    }
} 


 2. Read: Program - SerialRead.java

import java.io.*;


class SerialRead{
    public static void main(String[] args) throws Exception{
        FileInputStream fis=new FileInputStream("details.txt");
        ObjectInputStream ois=new ObjectInputStream(fis);
        A temp=(A)ois.readObject();
        temp.display();
        ois.close();
    }
} 

Compile both of the Java programs using command prompt and first execute the write and then read files.