Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Friday, July 4, 2014

What is Serialization and Deserialization in Java ?

Serialization :

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();
}
}


//Test3Write.java---> shows object writing (Serialization )

import java.io.*;
class Test3Write 
{
public static void main(String[] args)throws IOException 
{
Test3 t3=new Test3();
t3.setAccHName("Diehardtechy");
t3.setUserName("Techy");
t3.setPassword("123456");
t3.setBalance(45000);

System.out.println(t3);

ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("objectinfo.ser"));
oos.writeObject(t3);
}
}

//Test3Read.java---> shows object state reading  (Deserialization)

import java.io.*;
class Test3Read 
{
public static void main(String[] args) throws Exception
{
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("objectinfo.ser"));

//casting return object to Test# class object
Test3 t3=(Test3)ois.readObject();

System.out.println(t3);

}
}












No comments: