Friday, July 4, 2014

What is Serialization and Deserialization in Java ?

12:29 AM

Serialization is the process of converting objects into stream bytes and sending them to underlying OutputStream. Using serialization we can store object state permanently in a destination , for example file or remote computer.

Serialization operation is performed by writeObject() method of ObjectOutStream.

Deserialization :

Deserialization is the process of converting stream of bytes into original Object. Deserialization operation is performed by readObject() of ObjectInputStream class.

Rule on Serialization:

Only java.io.Serializable type objects are serialized. Serializable is a marker interface, it doesn't have any methods. It provides special permission or identity to JVM to serialize object.

If the given object isn't of type Serializable interface then writeObject() will throw an unchecked Exception called java.io.NotSerializableException.

Example to demonstrate serialization and Deserialization:

Below application shows writing Test3 class object to file.

//Test3.java

import java.io.*;

class Test3 implements java.io.Serializable

{

public double minBalance=5000.0;

private String accHName;

private String userName;

private String password;

private double balance;

public void setAccHName(String accHName)

{

this.accHName=accHName;

}

public String getAccHName()

{

return accHName;

}

public void setUserName(String userName)

{

this.userName=userName;

}

public String getUserName()

{

return userName;

}

public void setPassword(String password)

{

this.password=password;

}

public String getPassword()

{

return password;

}

public void setBalance(double balance)

{

this.balance=balance;

}

public double getBalance()

{

return balance;

}

public String toString()

{

return "Account holder name is "+getAccHName()+"\nAccount UserName is "+getUserName()+"\nAccount password is "+getPassword()+"\n Your current balance is "+getBalance();