What is Serialization?
Note: Here, your mind may ping you with a question that ‘What is an Object State’? Attribute values of an object is the state of an object.
As we are writing object state to file system or any persisting media anyone can able to access it. So, serialization is an unsecured operation. By default, java environment is not allowing to do any un-secured operation. In order to do a un-secured operation an object needs a mark in java. So, we have to use a Serializable, a marker interface which provides mark to an object. Serializable interface doesn’t have any methods. It just provides only mark to the objects to perform serialization in java. Let us see an example of Serialization in java using Serializable interface.
Consider the following program for which we are going to serialize its object.
In java, Serialization is a mechanism which allows us to convert an
object state to a byte stream that we can write it to persisting media
such as file system, database or any network.
Note: Here, your mind may ping you with a question that ‘What is an Object State’? Attribute values of an object is the state of an object.
As we are writing object state to file system or any persisting media anyone can able to access it. So, serialization is an unsecured operation. By default, java environment is not allowing to do any un-secured operation. In order to do a un-secured operation an object needs a mark in java. So, we have to use a Serializable, a marker interface which provides mark to an object. Serializable interface doesn’t have any methods. It just provides only mark to the objects to perform serialization in java. Let us see an example of Serialization in java using Serializable interface.
Consider the following program for which we are going to serialize its object.
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; class A implements Serializable { int i; int j; public static void main(String args[]) throws Exception { A a1 = new A(); a1.i = 10; a1.j = 20; FileOutputStream fout = new FileOutputStream("D:\\test.txt"); ObjectOutputStream out = new ObjectOutputStream(fout); out.writeObject(a1); out.flush(); out.close(); } }Now compile the preceding program and run it, so that you will find a text file created as 'test' inside D drive in your machine. If you open the test.txt file you can observe the state of the object saved in byte code. Thus we are saving the object state by implementing Serializable interface in java and this mechanism is known as 'Serialization'.