Home ProgrammingJava Serialization in Java

Serialization in Java

by Log Raj Bhatt
0 comment 1230 views

Serialization in java is just a process of converting objects into sequence of bytes due to the intention of transmitting it over channel. We consider some formal definitions here.

the process of writing state of object to file is called Serialization. It is process of converting object from java supported form to either file or network supported form. Whenever we pass object over ObjectOutputStream the serialization happens automatically. To serialize an object, the corresponding class of object must implement Serializable interface.

You may think where Serialization is useful. Very simple whenever we need to store or transmit the state of object we do serialization. For example if you want to store level of of your game application so that player can start where he has left, Serialization can be used. It is useful for developing cache supporting java program and in much more cases.

Object is deserialized while it is retrieved in application. it is reverse process of serialization. It is the process of converting an object from file or network supported form to java supported form. Or we can say it is the process of reading state of object from file or network.

Serialization in java

We will go through small example but before let’s talk about transient keyword.

In natural English language transient means temporary or that is short live. So the variables declared as transient are not serialized directly. Default value of transient variable is passed instead of original value after serialization. For example if we have a instance variable String id=”g132d”;  While serializing id will passed with default value of string null instead of “g132d”. And remember one thing transient  can only applied to the variables.

Now Look at an example.

import java.io.*;
class Test implements Serializable{
	String name="Log Raj";
	transient String id="2341f";
	int age= 20;

 class Serialize{
	public static void main(String args[]) throws Exception{
	 Test t1=new Test();
	FileOutputStream fos= new FileOutputStream("Myfile.txt");
	ObjectOutputStream oos=new ObjectOutputStream(fos);
	oos.writeObject(t1);  // object is serialized here
	/* Later on 
           we can deserialize
           the object

	FileInputStream fis=new FileInputStream("Myfile.txt");
	ObjectInputStream ois=new ObjectInputStream(fis);
	Test t2=(Test)ois.readObject();  // Object is deserialized here
	System.out.println(t2.id+":::::"+ t2.name+":::::"+ t2.age);

Explanation: Here the object t1 is serialized. And later deserialized. Here the id is declared transient so we will lose its value after deserialization. So as expected output is:



  • Import java.io package
  • Handle unchecked exceptions
  • Implement Serializable interface

Fore further query comment down….

0 comment

Related Articles

Leave a Reply

Do NOT follow this link or you will be banned from the site!