Serilization, deserialization & Externilization

Serialization Deserialization & Externalization, important interview topic

 1,067 total views

In this series of article we will be looking into one of the most important topic with respect to Interview and strengthen our coding skills by applying the same.  We are going to learn about Serialization Deserialization & Externalization, and must know Interview Questions and Answer.

What is Serialization?

Serialization is the conversion of a Java object into byte stream(sequence), which we can be stored into database or transfer over a network. Below points to needs to be remembered while implementing serialization:

  • Classes that are eligible for serialization need to implement a special marker interface, Serializable.
  • The JVM allows special privileges to the class which implements the Serializable Interface. Byte stream is platform-independent. This means that once you have a stream of bytes you can convert it into an object and run it on any kind of environment.

A class to be serialized successfully, two conditions must be met:

  1. The class must implement the java.io.Serializable interface.
  2. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.
//Implementing a employee type class 
import java.io.Serializable;

public class Employee implements Serializable {
	String empName;
	int empAge;
	double empSalary;
	
	public Employee(String empName, int empAge, double empSalary)
	{

		this.empName = empName;
		this.empAge = empAge;
		this.empSalary = empSalary;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public int getEmpAge() {
		return empAge;
	}

	public void setEmpAge(int empAge) {
		this.empAge = empAge;
	}

	public double getEmpSalary() {
		return empSalary;
	}

	public void setEmpSalary(double empSalary) {
		this.empSalary = empSalary;
	}
}
// Java Program to show serialization mechanism

// Importing Required classes/Interfaces
import java.io.*;
import java.util.*;


// Class implementing serializable interface
class SerializableDemo implements Serializable {

	public static void main(String[] args) throws Exception
	{

		// Creating an object of class in main() method
		Employee emp
			= new Employee("Ram", 34, 23646.00);

		// Saving of object in a file
		FileOutputStream fileOutputStream
			= new FileOutputStream("demo/serializableDemo.ser");
		ObjectOutputStream objectOutputStream
			= new ObjectOutputStream(fileOutputStream);

		// Method for serialization of object
		objectOutputStream.writeObject(emp);

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

In above example, the file output stream will create a file in the mentioned location with name “serializableDemo.sc”. This will have the state of the object in byte stream.

Click here for more off-campus freshers job

What is Deserialization?

Deserialization is precisely the opposite of serialization i.e Deserialization is the conversion byte stream(sequence) into objects or simpler form , which we can and easily readable and used for further utilization. That means with deserialization, you start with a byte stream and re-create the object you previously serialized in its original state. However, you must have the definition of the object to successfully re-create it.

 

// Java Program to show Deserialization mechanism

// Importing Required classes/Interfaces
import java.io.*;
import java.util.*;


// Class implementing serializable interface
class DeserializableDemo implements Serializable {

	public static void main(String[] args) throws Exception
	{

		// Creating an object of class in main() method
		DeserializableDemo emp
			= new DeserializableDemo("Ram", 34, 23646.00);

		// Saving of object in a file
		FileOutputStream fileOutputStream
			= new FileOutputStream("demo/DeserializableDemo.ser");
		ObjectOutputStream objectOutputStream
			= new ObjectOutputStream(fileOutputStream);

		// Method for serialization of object
		objectOutputStream.writeObject(emp);

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

		FileInputStream fileInputStream
			= new FileInputStream("demo/DeserializableDemo.ser");
		ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

		// Method for deserialization of object
		Employee emp1
			= (Employee)objectInputStream.readObject();

		// Display message only
		System.out.println("Employee Object has been deserialized ");

		// Print and display the name and age
		// to illustrate Serializable
		System.out.println("Name:" + emp1.getEmpName + "\n"
						+ "Age:" + emp1.getEmpAge + "\n"
						+ emp1.getEmpSalary);
	}
}

What is Externalization?

Whenever you need to customize serialization mechanism, Externalization comes into the picture. So, Externalization is used to customize the classes as per the serialization mechanism. To achieve this, externalization have two methods in it.

In serialization, the Java Virtual Machine is totally responsible for the process of writing and reading objects. This is useful in most cases, as the programmers do not have to care about the underlying details of the serialization process.

If programmers are using serialization and what if they want to secure some information during the serialization process?

However, the default serialization does not protect sensitive information such as passwords and credentials. Thus externalization comes to give the programmers full control in reading and writing objects during serialization. JVM has no control over it. The complete serialization control goes to the application.

Based on our requirements, we can serialize either the whole data field or a piece of the data field using the externalizable interface which can help to improve the performance of the application.

Register and submit your resume with us

Important points with respect to Externalization

  • Externalizable interface internally extends Serializable interface.
  • Externalizable interface is not a marker interface like Serializable interface.

Since Externalizable interface is not a markup interface, it provides two methods that are as follows:

  1. void readExternal(ObjectInput inStream) : We call readExternal() method when we want to read an object’s fields from a stream. We need to write logic to read an object’s fields inside the readExternal() method. The readExternal() method throws IOException when an I/O error occurs. If the class of object being restored does not find, ClassNotException will be thrown.
  2. void writeExternal(ObjectOutput outStream)  : writeExternal() method is used when we want to write an object’s fields to a stream. We need to write the logic to write data fields inside writeExternal() method. This method can throw an IOException when an I/O error occurs.

 

// Java Program to illustrate Externalizable

import java.io.*;
import java.util.*;

public class ExternalizableDemo implements Externalizable {

	String empName;
	int empAge;
	int empSalary;
	public ExternalizableDemo()
	{
		
	}

	public Employee(String empName, int empAge, double empSalary)
	{

		this.empName = empName;
		this.empAge = empAge;
		this.empSalary = empSalary;
	}

	public void writeExternal(ObjectOutput out)
		throws IOException
	{
		out.writeObject(empName);
		out.writeInt(empAge);
		out.writeInt(empSalary);
	}

	public void readExternal(ObjectInput in)
		throws IOException, ClassNotFoundException
	{
		empName = (String)in.readObject();

		empAge = in.readInt();
	}

	public static void main(String[] args) throws Exception
	{

		ExternalizableDemo t1 = new ExternalizableDemo("Ram", 35, 56454.00);

		FileOutputStream fos = new FileOutputStream("demo/ExternalizableDemo.ser");

		ObjectOutputStream oos = new ObjectOutputStream(fos);

		oos.writeObject(t1);

		FileInputStream fis = new FileInputStream("demo/ExternalizableDemo.ser");

		ObjectInputStream ois = new ObjectInputStream(fis);

		ExternalizableDemo t2 = (ExternalizableDemo)ois.readObject();

		System.out.println("Name :"
						+ " " + t2.empName + " "
						+ "Age :"
						+ " " + t2.empAge);
	}
}

Diference between Serialization, Deserialization and Externalization

Serialization Deserialization Externalization
Serialization is mechanism to convert the objects into byte stream. Serialization is mechanism to convert the byte stream into object. Externalization is used to customize the classes as per the serialization mechanism.
Serializable is a marker interface i.e. it does not contain any method   The externalizable interface is not a marker interface and thus it defines two methods writeExternal() and readExternal().
Serializable interface passes the responsibility of serialization to JVM and the programmer has no control over serialization, and it is a default algorithm.   The externalizable interface provides all serialization responsibilities to a programmer and hence JVM has no control over serialization.
Default serialization does not require any no-arg constructor.    A public no-arg constructor is required while using an Externalizable interface.
It is hard to analyze and modify class structure because any change in structure may break serialization.   It is relatively easy to analyze and modify class structure because of complete control over serialization logic.
Transient keywords play an important role here to customize the object based on the requirements.   Transient keywords won’t play any role. Externalization have two methods to handle customization
Difference between Sterilization, Deserialization, Externalization

 

 

Leave a feedback

We use cookies to improve your experience on our website. By browsing this website, you agree to our use of cookies.

Cart

Basket

Share

%d bloggers like this: