Please navigate to the bottom of the page for Table of Contents

Sunday, June 19, 2011

JAVA serialization interview question

Question: Explain serialization in JAVA with a basic example and write the data to a file.

Serialization allows to save/restore objects state from some (generally persistent) storage medium. Serialization allows you to save the state of the object and all its instance variables except those explicitly marked as transient.

Basic serialization is managed with just two methods:

  • ObjectOutputStream.writeObject() - serialize objects and write them to a stream,
  • ObjectInputStream.readObject()  - read the stream and deserialize objects.

The java.io.ObjectOutputStream and java.io.ObjectInputStream classes are considered to be higher-level classes in the java.io package and we need to wrap them around lower-level classes, such as java.io.FileOutputStream and java.io.FileInputStream.

import java.io.*;

class Circle implements Serializable { }

public class SerializeCircle
{
public static void main(String[] args)
{
Circle c = new Circle();
try
{
FileOutputStream fs = new FileOutputStream("data.txt");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
}
catch (Exception e)
{
e.printStackTrace();
}

try
{
FileInputStream fis = new FileInputStream("data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (Cat) ois.readObject();
ois.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}


Note that the Circle class implements the Serializable interface. Serializable is a marker interface; it has no methods to implement.

2 comments:

  1. Good question!!!

    I have also added some 2000 odd Core Java and J2EE questions in

    Java Interview Questions

    Have a look at them and reply.

    ReplyDelete