Serialization in Java with Example
Serialization in Java is the way toward changing over an object into bytes stream to spare it in the document.
Or then again we can say that serialization is utilized to continue (spare) the condition of an object.
The way toward reproducing the object from bytes stream is called deserialization.
Beneath I have referenced not many utilizations of serialization in Java.
Employments of Serialization
- To persevere the condition of an object for sometime later.
- To send an object on organizing.
- To store client session in electronic applications.
- To serialize an object, its class must execute the Serializable interface.
The Serializable interface doesn’t have any part thus it is called a marker interface. It tells the Java compiler that the object is serializable.
To make a few information individuals non-serializable, we should announce them as transient.
ObjectOutputStream and ObjectInputSteam are two classes that contain methods to serialize and deserialize an object.
writeObject() method of ObjectOutputStream class is utilized to compose an object to record.
readObject() method of ObjectInputStream class is utilized to peruse an object from record.
It is a Java show to give .ser augmentation to the record in which we are sparing the object.
Let’s take one example to see how serialization and deserialization are 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:
You can see in above yield that estimation of age variable is 0, which is the default estimation
of whole number sort variable. This shows transient information individuals can’t be serialized. You should likewise note in above code that when we read the object from
the document it must be type thrown into relating class type.
Beneath I have included a video that will assist you with learning the idea of serialization in Java.
In the event that you discovered anything off base or have any questions in regards to above instructional
exercise, then don’t hesitate to ask by remarking beneath.