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. 

What is Serialization

Java Serialization is a process in which the current state of Object will be saved in the stream of the byte. The byte stream is platform neutral hence once an object is created in one system, can be deserialized in other platforms.

What is the use of Serialization

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

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

Serialization and Deserialization in Java

Now we know what serialization is. But we need to understand how to achieve it in Java and how will it work.

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 the given interface.

Note*: Serializable Interface is a Marker Interface. Hence there is no method in the 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 the console.

Output would be

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

Bullet Points

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

In next article, we will talk about the use of Transient variable.

 

<< Java Hashmap tutorial Java Serialization concept & Example Part II >>

18 Comments Java serialization concept and Example

  1. New Dev

    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

    Reply
    1. Gagandeep

      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.

      Reply
    2. Rahul Mandhan

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

      Reply
  2. Vinayak

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

    Could you please help?

    Reply

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.