Java serialization concept and Example

Here i will learn and teach you what is Serialization in Java and how to write code for the same. I am learning this because i am going for an Interview. 😛

What is Serialization

Serialization is a process in which current state of Object will be saved in stream of bytes. As byte stream create is platform neutral hence once objects created in one system can be deserialized in other platform.

What is the use of Serialization

As written above serialization will translate the Object state to Byte Streams. This Byte stream can be used for different purpose.

  • Write to Disk
  • Store in Memory
  • Sent byte stream to other platform over network
  • Save byte stream in DB(As BLOB)

 

Serialization and Deserialization in Java

Now we know what is serialization. But in terms of Java how this serialization will work and how to make a class serializable. Java has already provided out of the box way(java.io.Serializable  Interface) to serialize an Object. If you want any class to be serialized then that class needs to implement give interface.

Note*: Serializable Interface is a Marker Interface. Hence there is no method in Serializable interface.

 

Code for Serialization of Java Class

Employee.java


package com.jbt;

import java.io.Serializable;

public class Employee implements Serializable
{
   public String firstName;
   public String lastName;
   private static final long serialVersionUID = 5462223600l;
}

 

SerializaitonClass.java


package com.jbt;

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

public class SerializaitonClass {

	public static void main(String[] args) {
		Employee emp = new Employee();
		emp.firstName = "Vivekanand";
		emp.lastName = "Gautam";

		try {
			FileOutputStream fileOut = new FileOutputStream("./employee.txt");
			ObjectOutputStream out = new ObjectOutputStream(fileOut);
			out.writeObject(emp);
			out.close();
			fileOut.close();
			System.out.printf("Serialized data is saved in ./employee.txt file");
		} catch (IOException i) {
			i.printStackTrace();
		}
	}
}

 

DeserializationClass.java


package com.jbt;

import java.io.*;

public class DeserializationClass {
	public static void main(String[] args) {
		Employee emp = null;
		try {
			FileInputStream fileIn = new FileInputStream("./employee.txt");
			ObjectInputStream in = new ObjectInputStream(fileIn);
			emp = (Employee) in.readObject();
			in.close();
			fileIn.close();
		} catch (IOException i) {
			i.printStackTrace();
			return;
		} catch (ClassNotFoundException c) {
			System.out.println("Employee class not found");
			c.printStackTrace();
			return;
		}
		System.out.println("Deserializing Employee...");
		System.out.println("First Name of Employee: " + emp.firstName);
		System.out.println("Last Name of Employee: " + emp.lastName);
	}
}

First run “SerializaitonClass” and you will get “employee.txt” file created.

Second run “DeserializationClass” and java will deserialize the class and value will be printed in console.

Output would be


Deserializing Employee...
First Name of Employee: Vivekanand
Last Name of Employee: Gautam

 

Bullet Points

  • Serialization interface needs to be implemented in order to make object serialized.
  • Transient instance variable doesn’t serialized with Object state.
  • If Super class implements Serializable then sub class are also Serializable automatically.
  • If Super class is not serializable then when sub class is de serialized then super class’s default constructor will be invoked. Hence all variable will get default value and reference will be null.

In Next Article i will discuss some advance part of Serializable.

 

Series Navigation<< Java String TutorialJava serialization concept and Example Part II >>
By | 2013-12-28T13:32:14+00:00 December 28th, 2013|Core Java|18 Comments

About the Author:

18 Comments

  1. New Dev May 15, 2014 at 12:41 pm - Reply

    when i run “SerializaitonClass” im getting following error. Not sure where is this going wrong
    SerializationClass.java:10: error: cannot find symbol
    Employee emp = new Employee();
    ^
    symbol: class Employee
    location: class SerializationClass
    SerializationClass.java:10: error: cannot find symbol
    Employee emp = new Employee();
    ^
    symbol: class Employee
    location: class SerializationClass
    2 errors

    • Gagandeep July 20, 2016 at 12:30 pm - Reply

      Error : “Cannot find symbol”
      It is encountered when either the symbol is not visible or found out of scope.
      Perhaps the class “Employee” could also not be imported.

    • Rahul Mandhan July 22, 2016 at 5:05 am - Reply

      You should create and import Employee class then run your serialization program sure it would run successfully…

  2. Anantha November 19, 2014 at 10:03 am - Reply

    Hi In this post there is typo. Serializable Interface is a Market Interface. Please change into Marker Interface.

  3. sandhya August 16, 2015 at 11:23 pm - Reply

    gud way to describe and practice for interview…i will also try the sam concept..:)

  4. Naresh October 25, 2015 at 1:29 pm - Reply

    good example….

  5. Nandini December 18, 2015 at 10:52 am - Reply

    hey here you have given one file name know “./employee.txt”, where that file will store actually.

    • J Singh December 18, 2015 at 5:50 pm - Reply

      . (dot) means current directory. So it will be stored in same directory as source file. Hope it help.

    • sachin December 27, 2015 at 8:54 pm - Reply

      in the current working directory file is saved

    • anonymous August 11, 2016 at 12:18 pm - Reply

      Its descendant you know , Learn Xml first

    • sdjbbdfjkv February 8, 2017 at 6:08 am - Reply

      your work space in current dictory

  6. Ankush January 19, 2016 at 12:37 pm - Reply

    Good One , Thank You for this great help 🙂 …

  7. Surya April 28, 2016 at 10:26 am - Reply

    not working, getting ClassCastException in the line “emp = (Employee) in.readObject();”

    can you help ?

  8. :) May 7, 2016 at 8:31 am - Reply

    thank you…..!!
    😀

  9. :) May 7, 2016 at 8:32 am - Reply

    😀 ty

  10. Guruprasad May 26, 2016 at 2:25 am - Reply

    But in spring framework why we need to serialise the models?

  11. ashok August 29, 2016 at 9:58 am - Reply

    thank you 🙂

  12. Vinayak September 28, 2017 at 8:56 am - Reply

    ObjectOutputStream and ObjectInputStream implement the Autocloseable interface, then why we explicitly closing these two streams in the code.?

    Could you please help?

Leave A Comment