Serialization in Java with Example

Serialization in Java is the process of converting an object into bytes stream to save it in file. Or we can say that, serialization is used to persist (save) the state of an object.

The process of recreating object from bytes stream is called deserialization.

Below I have mentioned few applications of serialization in Java.

Uses of Serialization

To persist the state of an object for future use.
To send an object on network.
To store user session in web based applications.

Serialization in Java with Example

Image Source

To serialize an object, its class must implement Serializable interface.

Serializable interface does not have any member and so it is called as marker interface. It tells the Java compiler that the object is serializable.

To make some data members non serializable, we must declare them as transient.

ObjectOutputStream and ObjectInputSteam are two classes that contain methods to serialize and deserialize an object.

writeObject() method of ObjectOutputStream class is used to write an object to file.

readObject() method of ObjectInputStream class is used to read an object from file.

It is a Java convention to give .ser extension to the file in which we are saving the object.

 

Lets take one example to understand how serialization and deserialization is done in Java.

 

Serialization and Deserialization Example

import java.io.*;

class Employee implements Serializable {
	String name;
	int salary;
	transient int age;
	
	Employee(String name,int salary,int age) {
		this.name=name;
		this.salary=salary;
		this.age=age;
	}
	
	public static void main(String...s) {
		Employee e=new Employee("neeraj mishra",50000,21);
		
		try {
			FileOutputStream fout=new FileOutputStream("data.ser");
			ObjectOutputStream out=new ObjectOutputStream(fout);
			out.writeObject(e);
			
			FileInputStream fin=new FileInputStream("data.ser");
			ObjectInputStream in=new ObjectInputStream(fin);
			
			e=(Employee)in.readObject();
			System.out.println(e.name);
			System.out.println(e.salary);
			System.out.println(e.age);
		} catch(Exception E) {
			E.printStackTrace();
		}
	}
}

 

Output

Serialization

You can see in above output that value of age variable is 0, which is the default value of integer type variable. This shows that transient data members can’t be serialized. You must also note in above code that when we read the object from file it must be type casted into corresponding class type.

Below I have added a video that will help you to learn concept of serialization in Java. If you found anything incorrect or have any doubts regarding above tutorial then feel free to ask by commenting below.

Leave a Comment

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