What is object Serialization? Explain the use of Persisting object.
1. Persisting the state of an object in a storage media is known as Object Serialization
2. Saving and retrieving data is one of the critical tasks for developers
3. By persisting objects, applications can efficiently handle them, as only one object can be used at a given point of time.
4. Object Serialization allows the objects to move from one computer to another by maintaining their state
5. Object Serialization implements the java.io.Serialization interface with few lines of code
- The following is the class declaration to serialize an object
public class UserData implements java.io.Serializable
6. When an application uses objects, it will not use all objects at once.
7. The required objects can be deserialized ( reading from stream) and handle it.
8. Later another object is handled, thus the heap memory space is conserved better. Hence the application can attain the efficiency
Depict the step of using object Deserialization.
Deserialization is to retrieve the serialized object into the java application
The following are the steps to deserialize an object:
1. Create an object of ObjectInputStream class.
2.Read the object by using the method readObject()
3. Manipulate the data available in the deserialized object based on the application’s demand.
4. Close the streams.
The following is the code example to deserialize the object. import java.io.*;
public class DeserializeEmployee
{
public static void main(String[] args)
{
FileInputStream fileIn=null;
ObjectInputStream objIn=null;
fileIn= new FileInputStream(“Employee.ser”);
objIn = new ObjectInputStream(fIn);
//de-serializing employee
Employee emp = (Employee) objIn.readObject();
// Employee name and designation were serialized
System.out.println(“Employee name ” + emp.name + ” \nEmployee designation “ + emp.desig);
objIn.close();
fileIn.close();
}
}