Object Serialization/De-serialization
Java provides the ability to save objects in a byte-stream that can be later used to transfer objects across the networks, or can be saved to disk in the file, or can be stored in the database and later can be reconstituted to reclaim the objects. Object serialization is useful in several real-world applications and especially in the remote method invocation and distributed computing applications.Java beans and EJBs also use this aspect of java. This feature of java is known as serialization and reconstruction of the serialized object is known as de-serialization.
The objects of any class which implements the Serializable interface can be serialized only. ObjectInputStream and ObjectOutputStream allows serialization and de-serialization. There are various other classes and interfaces provide specific support for the serialization process. The keyword transient provides a language level means of making data that should not be de-serialized.
![]() |
Serializtion/De-serialization |
Serialization
//Serialization
import java.io.FileOutputStream;
object serialized
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Box implements Serializable{
int h,w,l;
public Box(int h, int w, int l) {
super();
this.h = h;
this.w = w;
this.l = l;
}
public void displayVolume()
{
System.out.println("Box
Volume: "+h*w*l);
}
}
public class TestSerialization {
public static void main(String[] args) throws IOException, ClassNotFoundException{
//serializing
FileOutputStream fos=new FileOutputStream("store.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
Box b=new Box(23,12,10);
oos.writeObject(b);
oos.flush();
oos.close();
System.out.println("object
serialized");
}
}
Output:
Deserialization
//Deserialization
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
class Box implements Serializable{
int h,w,l;
public Box(int h, int w, int l) {
super();
this.h = h;
this.w = w;
this.l = l;
}
public void displayVolume()
{
System.out.println("Box
Volume: "+h*w*l);
}
}
public class TestSerialization {
public static void main(String[] args) throws IOException, ClassNotFoundException{
//deserialization
FileInputStream fis=new FileInputStream("store.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Box b=(Box)ois.readObject();
System.out.println("Object
retrieved");
b.displayVolume();
}
}
Output:
Object retrieved
Box Volume: 2760
Video Tutorial