1.

Serialization vs Deserialization in Java

Answer»

Serialization in JAVA involves writing the object state into a byte stream so that it can be SENT to a database or a disk. Deserialization is the reverse PROCESS wherein the stream is converted into the object.

The java.io.Serializable interface is implemented by default by the String class as well as all the wrapper classes. The functionality to serialize the objects is provided by the writeObject() method of ObjectOutputStream class. Deserialization of objects and primitive data is done using ObjectInputStream.

A program that demonstrates serialization and deserialization in Java is given as follows:

import java.io.*; class EMPLOYEE implements Serializable {    int empID;    String name;    Employee(int e, String n)    {        this.empID = e;        this.name = n;    } } public class Demo {    public static void MAIN(String[] args)    {        Employee emp1 = new Employee(251,"Jason Scott");          FileOutputStream f = new FileOutputStream("file.txt");          ObjectOutputStream o = new ObjectOutputStream(f);          o.writeObject(emp1);          o.flush();          ObjectInputStream i = new ObjectInputStream(new FileInputStream("file.txt"));          Employee emp2 = (Employee)i.readObject();          System.out.println(emp2.empID + " " + emp2.name);          i.close();      } }

The output of the above program is as follows:

251 Jason Scott


Discussion

No Comment Found