Serialization & Deserialization

Serialization –
  • Serialization is a process where the state of an object is converted into a byte stream.
  • The purpose is to travel an object across a network.
  • Implement the java.io.Serializable interface, to make a Java object serializable.
  • To serialize an object, use the writeObject() method of ObjectOutputStream class.
  • If a parent class has implemented a Serializable interface then the child class doesn’t need to implement it, however vice-versa is not true.
  • The serialization process only saves non-static data members.
  • The serialization process does not save static data members and transient data members.
  • While serializing an object, if we don’t want to serialize certain data members of the object, we can mention it transient. To prevent the serialization of a data member, use the transient keyword.
import java.io.*;


class Student implements Serializable {
	Student(String s) {
		//some code
	}
}
class Test {
	public static void main(String args[]) {
		try {
			Student si = new Student("Ram");
			FileOutputStream fos = new FileOutputStream("Student.ser");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(si);
			oos.close();
			fos.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Deserialization –
  • Deserialization is the reverse process of serialization. Here we recreate the actual Java object in memory, we use the byte stream. This mechanism is useful for reconstructing the object from the serialized state.
  • To deserialize an object, use the readObject() method of ObjectInputStream class.
  • When we deserialize an object, the constructor of an object is never called.
  • The byte stream created is platform-independent. So, if we serialize the object on one platform, we can deserialize it on a different platform.
import java.io.*;

class Test {
	public static void main(String args[]) {
		Student si = null;
		try {
			FileInputStream fis = new FileInputStream("Student.ser");
			ObjectInputStream ois = new ObjectInputStream(fis);
			si = (Student)ois.readObject();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}