Reading:  

Quick walk through the advanced concepts in Java - Part 3 of series


Serialization and De-serialization

Java provides a mechanism called object serialization where objectis represented as a sequence of bytes which includes object's data and information about object's type and types of data stored in object.

Once serialized object is been written into a file it can be read from file and deserialized that is type information and bytes that represent object and its data can be used to recreate object in memory.

Process of serialization and de-serialization is not dependent on JVM. What this means is that objects can be searialized on one computer and de-serialized on another. 

Classes ObjectInputStream and ObjectOutputStream are high-level streams which contain methods for serializingand deserializing an object.

The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out:

public final void writeObject(Object x) throws IOException

The above method serializes an Object and sends it to output stream. SimilarlyObjectInputStream class contains following method for deserializing an object:

public final Object readObject() throws IOException,ClassNotFoundException

This method retrieves next Object out of stream and deserializes it.

public class Student implements java.io.Serializable {
	public String name;
	public String address;
	public transient int studentID;
}

 

To implement serialization it should meet following condition:

  • The class should implement java.io.Serializable interface.
  • All of fields in class must be serializable. If a field is not serializable, it must be marked transient.

Serializing an Object:

The ObjectOutputStream class is used to serialize an Object. The following SerializeexampleDemo program instantiates an Student object and serializes it to a file.

When program is done executing, a file named student.ser is created.

import java.io.*;

public class SerializeexampleDemo {
	public static void main(String[] args) {
		Student Std = new Student();
		Std.name = "Nimrit";
Std.StudentID = 111;
		try {
			FileOutputStreamfileOutput = new FileOutputStream("/tmp/student.ser");
			ObjectOutputStream out = new ObjectOutputStream(fileOutput);
			out.writeObject(e);
			out.close();
			fileOutput.close();
			System.out.printf("Serialized data has been saved to /tmp/student.ser");
		} catch (IOExceptioni) {
			i.printStackTrace();
		}
	}
}

Deserializing an Object:

The following DeserializeexampleDemo program deserializesStudent object created in  SerializeexampleDemo program.

import java.io.*;
public class DeserializeexampleDemo {
	public static void main(String[] args) {
		Student std = null;
		try {
			FileInputStreamfileIn = new FileInputStream("/tmp/student.ser");
			ObjectInputStream in = new ObjectInputStream(fileIn);
			std = (Student) in .readObject(); in .close();
			fileIn.close();
		} catch (IOExceptioni) {
			i.printStackTrace();
			return;
		} catch (ClassNotFoundException c) {
			System.out.println("Student not found");
			c.printStackTrace();
			return;
		}
		System.out.println("Deserialized Student...");
System.out.println("Name: " + std.name);
System.out.println("SID: " + std.StudentID);
}
}

Output

Deserialized Student...
Name: Nimrit
SID: 0

 

Some key things you should know for above program

  • The try/catch block tries to catch a ClassNotFoundException, which declared by readObject() method.
  • Notice that return value of readObject() is cast to an Student reference.
  • The value of StudentID field was 111 when object was serialized but because field is transient, this value was not sent to output stream, thus the value of 0. 

 

 

Description

This is the last part in our tutorial series on Java. This tutorial is designed as a quick walk through the advanced concepts of Java Languages. This tutorial is subdivided into few chapters as shown below

  1. Data Structures
  2. Collections
  3. Generics
  4. Serialization
  5. Networking 
  6. Working with Emails
  7. Multithreading
  8. Getting started with Applets
  9. JavaDoc

Let us know if you find any issues with this tutorial. Also, if you can provide us with your feedback, that always help us improve.

 



Prerequisites

You must have read Part 1 and Part 2 of our tutorial series on Java.

Audience

Beginners or students looking to brush up their Java knowledge

Learning Objectives

To get an understanding on some of the advanced topics of Java.

Author: Subject Coach
Added on: 10th Mar 2015

You must be logged in as Student to ask a Question.

None just yet!