Serialization

 

An object asks “Whenever I’m created, I stay in the heap memory.  Is it possible for you to persist me somewhere? ”

Yes it is possible.

An object and its instance variables can be saved into a physical device.

Object serialization saves the state of an object as sequence of bytes and at later time the object is reconstituted from these bytes. Objects are serialized by object output stream and deserialized by object input stream.

The ObjectOutputStream class serializes Java objects. An ObjectInputStream deserialises objects previously written using an ObjectOutputStream.

ObjectOutputStream and ObjectInputStream can provide an application with persistent storage objects when used with a FileOutputStream and FileInputStream respectively.

 

import java.io.*;

class Car implements Serializable {
private String fuelType;
public Car(String fuelType) {
this.fuelType = fuelType;
}
public String getFuelType() {
return fuelType;
}
}

public class SerializableCar {

public static void main(String args[]) {
Car c = new Car(“diesel”);
FileOutputStream fos = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
FileInputStream fis = null;
try {
fos = new FileOutputStream(“D:\\jThread\\car.ser”);
oos = new ObjectOutputStream(fos);
oos.writeObject(c);
fis = new FileInputStream(“D:\\jThread\\car.ser “);
ois = new ObjectInputStream(fis);
Car c1 = (Car) ois.readObject();
System.out.println(c1.getFuelType());
} catch (Exception e) {
System.out.println(“File Not Found”);
} finally {
try {
fos.close();
fis.close();
ois.close();
oos.close();
} catch (IOException e1) {
System.out.println(“IO Exception while closing”);
}
}
}
}

Important :

The class whose object needs to be serialized must implement a marker interface called java.io. Serializable. Marker interfaces are interfaces with no methods. They just tell the compiler that the objects of the classes implementing the interfaces with no defined methods need to be treated differently. In serialization failing to implement Serializable interface will result in an exception thrown at runtime, i.e. java.io.NotSerializableException.

The instance variables(fields) which are marked as transient in a serializable object will not be transmitted in the byte stream. i.e. transient variables will not be serialized.

 

Saju Pappachen

 

About the author: Saju Pappachen is the Chief Consultant of jThread IT Training & Consultancy. He has more than 20 years of experience in Java technology.

He can be reached at saju@jthread.com

28 thoughts on “Serialization

Leave a Reply

Your email address will not be published. Required fields are marked *