A Serialization Example in Java

The following program illustrates how to use object serialization and deserialization. It begins by instantiating an object of class MyClass. This object has three instance variables that are of types String, int, and double. This is the information we want to save and restore.

A FileOutputStream is created that refers to a file named "serial," and an ObjectOutputStream is created for that file stream. The writeObject() method of ObjectOutputStream is then used to serialize our object. The object output stream is flushed and closed.

A FileInputStream is then created that refers to the file named "serial," and an ObjectInputStream is created for that file stream. The readObject() method of ObjectInputStream is then used to deserialize our object. The object input stream is then closed.

Note that MyClass is defined to implement the Serializable interface. If this is not done, a NotSerializableException is thrown. Try experimenting with this program by declaring some of the MyClass instance variables to be transient. That data is then not saved during serialization.

import java.io.*;
public class SerializationDemo {
public static void main(String args[]) {
// Object serialization
try {
MyClass object1 = new MyClass("Hello", -7, 2.7e10);
System.out.println("object1: " + object1);
FileOutputStream fos = new FileOutputStream("serial");
ObjectOutputStream oos = new ObjectOutputStream(fos);
catch(Exception e) {
System.out.println("Exception during serialization: " + e);
// Object deserialization
try {
MyClass object2;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
object2 = (MyClass)ois.readObject();
System.out.println("object2: " + object2);
catch(Exception e) {
System.out.println("Exception during deserialization: " +
class MyClass implements Serializable {
String s;
int i;
double d;
public MyClass(String s, int i, double d) {
this.s = s;
this.i = i;
this.d = d;
public String toString() {
return "s=" + s + "; i=" + i + "; d=" + d;

This program demonstrates that the instance variables of object1 and object2 are
identical. The output is shown here:

object1: s=Hello; i=-7; d=2.7E10
object2: s=Hello; i=-7; d=2.7E10

This tutorial is an extract from the "The Complete Reference Part 2 by Herbert Schildt".

COPYRIGHT © 2017 java-samples.com. ALL RIGHTS RESERVED.