Serialization in java

Why Serialization ?

  1. Used to re-create object into its original state (In another JVM).
  2. Converts object to stream of bytes for easy shipment of information.
  3. Saves the state of the object for recreation without having to reprocess them in different platform.

Concept : How serialization happens ?

  • DataStructure exist in all languages : Could be array, Object, Map etc
  • Diffuclut comes when we transfer the data structure over a network or store it in a file and another program reads it.
  • So to do that we serialise these data structure and store it in a file using seralization.
  • Seraization can be done use json, yml or xml and any such method. i.e just flating out into a string so that it can be recreated(deserialize) by another program once read

Java is planning to remove serialization from java language in future

package Layering;

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

class Demo implements java.io.Serializable {
	public int a;
	public String b;

	public Demo(int a, String b) {
		this.a = a;
		this.b = b;
	}

}

class Test {
	public static void main(String[] args) {
		Demo object = new Demo(1, "helloSeralization");
		String filename = "file.ser";

		try {
			FileOutputStream file = new FileOutputStream(filename);
			ObjectOutputStream out = new ObjectOutputStream(file);

			out.writeObject(object);

			out.close();
			file.close();

			System.out.println("Object has been serialized");

		}

		catch (IOException ex) {
			System.out.println("IOException is caught");
		}

		Demo object1 = null;

		try {
			FileInputStream file = new FileInputStream(filename);
			ObjectInputStream in = new ObjectInputStream(file);

			object1 = (Demo) in.readObject();

			in.close();
			file.close();

			System.out.println("Object has been deserialized ");
			System.out.println("a = " + object1.a);
			System.out.println("b = " + object1.b);
		}

		catch (IOException ex) {
			System.out.println("IOException is caught");
		}

		catch (ClassNotFoundException ex) {
			System.out.println("ClassNotFoundException is caught");
		}

	}
}

Leave a Comment