Serialization is the process of writing the state of an object to a byte
stream.
Serialization of Object
This class is writing an object of Student class to the Student.ser file. We are
using FileOutputStream and ObjectOutputStream to write the object to File.
import java.io.*;
class student implements Serializable
{
String name;
int rid;
static String contact;
student(string n, int r, string c)
{
this.name = n;
this.rid = r;
this.contact = c;
}
}
class Test
{
public static void main(String[] args)
{
try
{
student s = new student("Aman", 04, "9898744");
FileOutputStream fos = new FileOutputStream("student.ser");
Objectoutputstream oos = new ObjectOutputStream(fos);
oos.writeObject(s);
oos.close();
fos.close();
}
catch (Exception e)
{ e. printStackTrace(); }
}
}
Deserialization is the process of restoring these objects.
Deserialization of Object
import java.io * ;
class DeserializationTest
{
public static void main(String[] args)
{
student s=null ;
try
{
FileInputStream fis = new FileInputStream("student.ser");
ObjectOutputStream ois = new ObjectOutputStream(fis);
s = (student)ois.readObject();
}
catch (Exception e)
{ e.printStackTrace(); }
System.out.println(s.name);
System.out. println(s.rid);
System.out.println(s.contact);
}
Read More →Core Java Interview Questions
Object Oriented Programming(OOP) Questions and Answers
Collections Interview Questions
Java Exceptions Interview Questions
Java Threads Interview Questions
Collection framework in java interview questions
oops concepts with example in java
Java Serialization Interview Questions
Top 20 Core Java Interview Questions with Answers
String Interview Question in java With Example
synchronization interview questions
Java Reflection Interview question
Java Executor Framework (JDK 1.5) Interview Questions
JDK 1.7 interview Questations and Answers
Java I/O interview question with example