Java Serialization

Serialization is converting and object into a byte stream, for storing the object persistently or to transfer the object over the network. This is also called marshalling.

De serialization is converting a byte stream back to object. This is also called unmarshalling.

RMI(Remote Method Invocation) is based on Serialization.

data member declared as transient will not be serialized.

import java.io.*;

//Object which need to be serialized need to be implemented from Serializable interface
class studentinfo implements Serializable
{
//transient data members will not take part in Serialization
transient String name;
int rid;
double fee_paid;
String contact;
studentinfo(String n, int r, double fp,String c)
{
this.name = n;
this.rid = r;
contact = c;
this.fee_paid = fp;
}

void printStudentInfo()
{
System.out.println(“StudentInfo details Test:”+name+” “+rid+” “+contact+” “+fee_paid);
}
}

public class Main
{
public static void main(String[] args)
{
try
{
//Serialization starts here
studentinfo si = new studentinfo(“Somename”, 302,58.63, “110044”);
FileOutputStream fos = new FileOutputStream(“student.ser”);

ObjectOutputStream oos = new ObjectOutputStream(fos);

System.out.println(“Serialing the object…”);
oos.writeObject(si);
oos.close();
fos.close();
System.out.println(“De serializing object…”);

//DeSerialization starts here
FileInputStream fis = new FileInputStream(“student.ser”);
ObjectInputStream ois = new ObjectInputStream(fis);
studentinfo to = (studentinfo)ois.readObject();

System.out.println(“before printing Object”);

to.printStudentInfo();

//RMI(Remote Method Invocation) is based on Serialization/Deserialization
}
catch (Exception e)
{ e. printStackTrace(); }
}
}

2 thoughts on “Java Serialization”

Leave a Reply