InterviewSolution
| 1. |
Serialize and Deserialize an Object in Java |
|
Answer» Serialization is the process of CHANGING the state of an object into the byte stream so that the byte stream can return back into a copy of the object In Java, an object is SAID to be serializable if its class or parent classes IMPLEMENT either the Serializable interface or the Externalizable interface. Deserialization is CONVERTING the serialized object back into a copy of the object. During serialization, if we don’t want to write the state of the particular variable in the byte stream, we use the transient keyword. When the JVM comes up to the transient keyword, it ignores the original state of the variable and stores a default value of that data type i.e. 0 for int, 0 for byte, 0.0 for float,etc. Serialization of an object is done through the FileOutputStream and ObjectOutputStream. Suppose we create an object obj of class Example: Example obj = new Example();It is serialized as follows: FileOutputStream fos = new FileOutputStream("file_name.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(obj);The serialized object is deserialized using FileInputStream and ObjectInputStream. The byte stream reverts back to the copy of the object i.e. x FileInputStream fis = new FileInputStream("file_name.txt"); ObjectInputStream ois = new ObjectInputStream(fis); Example x = (Example)ois.readObject();Let us see an program for serialization along with deserialization of an object named obj : import java.io.*; public class Example implements Serializable { int a = 1, b = 2; // instance variable transient int c = 3; // transient variable public static void main(String[] args) throws Exception { Example obj = new Example(); // serialization FileOutputStream fos = new FileOutputStream("example_file.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(obj); // de-serialization FileInputStream fis = new FileInputStream("example_file.txt"); ObjectInputStream ois = new ObjectInputStream(fis); Example x = (Example)ois.readObject(); System.out.println("a = " + x.a); System.out.println("b = " + x.b); System.out.println("c = " + x.c); } }The output is as follows: $javac Example.java $java Example a = 1 b = 2 c = 0 |
|