Serialization

The process of saving an object to a file is called “Serialization”.But strictly speaking,it is the process of converting an object from Java supported format to either file supported format or network supported format.

By using FileOutputStream and ObjectOutputStream ,we can perform serialization.
Serialization

DeSerialization

The process of reading an object from a file is called DeSerialization.But strictly speaking de serialization is the process of converting an object from file or network supported format to Java supported format.

By using FileInputStream and ObjectInputStream classes,we can achieve DeSerialization.
DeSerialization

Example:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Dog implements Serializable {
	
	int i=10;
	int j=20;
}

public class SerializeDemo {
	public static void main(String[] args)throws Exception {
		
		//Serialization
		Dog d=new Dog();
		FileOutputStream fos=new FileOutputStream("abc.ser");
		ObjectOutputStream oos=new ObjectOutputStream(fos);
		oos.writeObject(d);
		
		//De-Serialization
		FileInputStream fis=new FileInputStream("abc.ser");
		ObjectInputStream ois=new ObjectInputStream(fis);
		Dog d2=(Dog)ois.readObject();
		
		System.out.println(d2.i+"----"+d2.j);
	}
}
/*
Output:
10----20
*/
  1. We can perform serialization only for serializable objects.An object is said to be serializable if only if the corresponding class should implement Serializable interface.
  2. Serializable interface is defined in java.io package and doesn’t contain any method ,It is a marker inetrface.
  3. If we are trying to perform serialization of non-serializable objects,We will get RuntimeException saying “NotSerializableException“.
  4. At the time of serialization,If you don’t want to send the value of a particular variable,We have to declare that variable as transient.
  5. At the time of serialization ,JVM ignores the original value of transient variable and send default value.i.e transient means not to serialize.

  6. static variables are not part of the object,Hence they won’t participate in serialization process.
  7. As static variables won’t participate in serialization,declaring static variable as transient there is no impact.
  8. Similarly,declaring final variable as transient there is no impact.
Declaration Output
int i=10;
int j=20;
10—20
transient int i=10;
int j=20;
0—20
transient static int i=10;
transient int j=20;
10—0
transient final int i=10;
transient int j=20;
10—0