Serialization & De-serialization in Java

When you create a class, you may create an object for that particular class and once we execute/terminate the program, the object is destroyed by itself (Garbage Collector thread).

What happens if you want to call that class without re-creating the object. In those cases what you do is that, we use the serialization concept by convert data into byte stream.

Object Serialization is a process used to convert state of an object into byte stream which can be persisted into disk/file or sent over network to any other running Java virtual machine; and the reverse process of creating object from byte stream is called deserialization in Java.The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform.

How to make a java class Serializable ?
Serializability can be enabled of your java class by implementing the java.io.Serializable interface. It is a marker interface that means it contains no methods or fields and only serves to identify the semantics of being serializable.

What if we are trying to serialize a non-serializable object?
We will get RuntimeException saying :
Exception in thread “main” java.io.NotSerializableException: java.io.ObjectOutputStream.

What is serialVersionUID ?
SerialVersionUID is an ID which is stamped on object when it get serialized usually hashcode of object. We can find serialVersionUID for the object by serialver tool of java.
Syntax : serialver classname

SerialVersionUID is used for version control of object. Consequence of not specifying serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch.

transient keyword :
transient modifier/keyword applicable only for variables but not for methods and classes.
At the time of serialization if we don’t want to serialize the value of a particular variable to meet security constraints then we should declare that variable as transient.
While performing serialization JVM ignores original value of transient variable and save default value to the file.
Hence transient means not to serialize.

transient v/s static :
Static variable is not part of object state and hence it won’t participate in serialization. Due to this declaring static variable as transient, there is no use.

final v/s transient :
final variables will be participated in serialization directly by the value.Hence declaring a final variable as transient , there is no impact.

Now, let us consider a program which shows Serialization & De-serialization in java :

This POJO class Employee implements Serializable interface :

package com.java.serialization;

import java.io.Serializable;

public class Employee implements Serializable {

	private static final long serialVersionUID = 1L;
	
	private String serializeValueName;
	private transient int nonSerializeValueSalary;
	
	public String getSerializeValueName() {
		return serializeValueName;
	}
	public void setSerializeValueName(String serializeValueName) {
		this.serializeValueName = serializeValueName;
	}
	public int getNonSerializeValueSalary() {
		return nonSerializeValueSalary;
	}
	public void setNonSerializeValueSalary(int nonSerializeValueSalary) {
		this.nonSerializeValueSalary = nonSerializeValueSalary;
	}
	
	@Override
	public String toString() {
		return "Employee [serializeValueName=" + serializeValueName + "]";
	}
}

The following SerializingObject program instantiates an Employee object and serializes it to a file.

package com.java.serialization;

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


public class SerializingObject {

	public static void main(String[] args) {
		
		Employee employeeOutput = null;
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		
		employeeOutput = new Employee();
		employeeOutput.setSerializeValueName("Aman");
		employeeOutput.setNonSerializeValueSalary(50000);
		
		try {
			fos = new FileOutputStream("Employee.ser");
			oos = new ObjectOutputStream(fos);
			oos.writeObject(employeeOutput);
		
		System.out.println("Serialized data is saved in Employee.ser file");
		
		oos.close();
		fos.close();
		
		} catch (IOException e) {
			
			e.printStackTrace();
		} 
	}
}

OUTPUT :

Serialized data is saved in Employee.ser file.

The following DeSerializingObject program deserializes the Employee object created in the SerializingObject program.

package com.java.serialization;

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

public class DeSerializingObject {
	
	public static void main(String[] args) {
		
		Employee employeeInput = null;
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		
		try {
			fis = new FileInputStream("Employee.ser");
			ois = new ObjectInputStream(fis);
			employeeInput = (Employee)ois.readObject();
			
			System.out.println("Serialized data is restored from Employee.ser file");
			
			ois.close();
			fis.close();
			
		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
		} 
		
		System.out.println("Name of employee is : " + employeeInput.getSerializeValueName());
		System.out.println("Salary of employee is : " + employeeInput.getNonSerializeValueSalary());
	}
}

OUTPUT :

Serialized data is restored from Employee.ser file
Name of employee is : Aman
Salary of employee is : 0

 

Leave a Reply