Serialization in Java with Example and Interview questions

By | June 26, 2012
This article provide you the details about Serialization in Java with Example and Interview questions. The simple definition for the serialization is the mechanism that changing the object into byte format". The object can be represented as a sequence of bytes.

This Object includes the particular object data and information about the type of object. Once serialization is done object has been written into a file. We can read the file again and deserialize the object. The most important thing is that the serialization and deserialization process is JVM independent. It means that Object can be serialized into one platform and it can be deserialized in different platform.

How to Serialize and Deserialize Objects in Java?

ObjectOutputStream is used to Serialize object and ObjectInputStream is used for deserializaing mechanism. writeObject(Object x) method present in ObjectOutputStream class which used for serialization and readObject() method available in ObjectInputStream which is used for deserialization.
The methods as follows,

Import java.io.ObjectOutputStream;
public final void writeObject(Object x) throws IOException

Import java.io.ObjectInputStream;
public final Object readObject() throws IOException, ClassNotFoundException

This readObject() method deserialize the object and its return value is object. So we have to store it into appropriate data type.

Let we take one example program to perform both Serialization and deserialization.

Serialization and Deserialization in Java Example Program

EmployeeDetails.java

import java.io.*;

public class EmployeeDetails implements Serializable{

	public String name;
	public String bloodGroup;
	public int age;
	public transient int salary;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return the bloodGroup
	 */
	public String getBloodGroup() {
		return bloodGroup;
	}
	/**
	 * @param bloodGroup the bloodGroup to set
	 */
	public void setBloodGroup(String bloodGroup) {
		this.bloodGroup = bloodGroup;
	}
	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}
	/**
	 * @param age the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}
	/**
	 * @return the salary
	 */
	public int getSalary() {
		return salary;
	}
	/**
	 * @param salary the salary to set
	 */
	public void setSalary(int salary) {
		this.salary = salary;
	}

}
JavaSerializationProgram.java
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class JavaSerializationProgram {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		EmployeeDetails edObj=new EmployeeDetails();
		edObj.setName("EshuSoft");
		edObj.setBloodGroup("B +Ve");
		edObj.setAge(25);
		edObj.setSalary(20000);
		try{
			FileOutputStream fos=new FileOutputStream("Employee.dat");
			ObjectOutputStream out=new ObjectOutputStream(fos);
			out.writeObject(edObj);
			out.close();
			fos.close();

		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

JavaDeserializationProgram.java
import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class JavaDeserializationProgram {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		EmployeeDetails ed=null;

		try{
		FileInputStream fis=new FileInputStream("Employee.dat");
		ObjectInputStream in=new ObjectInputStream(fis);

		ed= (EmployeeDetails) in.readObject();

		}catch(Exception e){
			e.printStackTrace();
		}
		System.out.println("Deserialize Employee..");
		System.out.println("Name :"+ed.name);
		System.out.println("Blood Group :"+ed.bloodGroup);
		System.out.println("Age :"+ed.age);
		System.out.println("Salary :"+ed.salary);
	}
}

Note : If you get compile time exception like “Syntax error on token “transient”, delete this token”. Check the transient variable once it might be defined as public int transient objectName; but it should be public transient int objectName;

What is Serialization in Java?
Serialization is the process of converting state of an object to stream of bytes. The converted bytes can sent over the network (or) it can be stored into a particular file (or) we can store the converted bytes into database. We can reconstruct into Object whenever its required.

What is Externalization in Java ?
Externalization and Serialization both are same except writeObject(Object x) and readObject() methods called by JVM during Serialization an desterilization process of the Object. Other than this in Externalization we can store extra information into object like static and transient variables or also we can add some other information as per requirement.

Leave a Reply

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