Java – Serializable interface with example

In this article, we will discuss the important things we should know about java.io.Serializable interface in detail

1. Serializable interface:

  • Present in java.io package
  • Fully qualified class name is java.io.Serializable
  • It is a Marker interface which means a Java class implementing marker interface has got certain capability
  • It has no body i.e.; it doesn’t contain any methods
  • We can serialize, only serializable objects
  • An Object said to be Serializable, if its corresponding class implements java.io.Serializable interface
  • Serializing a non-serializable object results in throwing NotSerializableException exception during program execution
3-serialization-de-serialization-in-java

2. Demo example on Java Serialization & De-Serialization

  • For objects to participate in serialization and de-serialization process, corresponding class should implement java.io.Serializable interface
  • Otherwise, run time exception will be thrown stating NotSerializableException

Step 1: Create POJO which implements java.io.Serializable interface

  • we will create simple POJO implementing Serializable interface consisting couple of variables

Customer.java

  • Customer class is the one to be serialized
  • Therefore, it is must to implement java.io.Serializable interface
  • Consists of 3 member variables namely
  • Two integer members (customer id and customer age) and a String member (customer name)
package in.bench.resources.serialization;

import java.io.Serializable;

public class Customer implements Serializable {

	// member variables
	int customerId;
	String customerName;
	int customerAge;

	// 3-arg parametrized constructor
	public Customer(int customerId, String customerName,
			int customerAge) {
		super();
		this.customerId = customerId;
		this.customerName = customerName;
		this.customerAge = customerAge;
	}

	// overriding toString() method
	@Override
	public String toString() {
		return "Customer ["
				+ "customerId=" + customerId + ","
				+ " customerName=" + customerName + ","
				+ " customerAge=" + customerAge
				+ "]";
	}
}

Step 2: Serialization and De-Serialization together in one class

  • To Serialize any Object, we can use ObjectOutputStream and FileOutputStream to write/save to file in binary format
  • To De-Serialize any Object, we can use ObjectInputStream and FileInputStream to read/restore from file (which is in binary format) into Java heap memory

CustomerSerializeDeSerializeDemo.java

package in.bench.resources.serialization;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class CustomerSerializeDeSerializeDemo {

	public static void main(String[] args) {

		// create an customer object using 3-arg parametrized constructor
		Customer serializeCustomer = new Customer(102, "SR", 17);

		// creating output stream variables
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;

		// creating input stream variables
		FileInputStream fis = null;
		ObjectInputStream ois = null;

		// creating customer object reference
		// to hold values after de-serialization
		Customer deSerializeCustomer = null;

		try {
			// for writing or saving binary data
			fos = new FileOutputStream("Customer.ser");

			// converting java-object to binary-format
			oos = new ObjectOutputStream(fos);

			// writing or saving customer object's value to stream
			oos.writeObject(serializeCustomer);
			oos.flush();
			oos.close();

			System.out.println("Serialization: "
					+ "Customer object saved to Customer.ser file\n");

			// reading binary data
			fis = new FileInputStream("Customer.ser");

			// converting binary-data to java-object
			ois = new ObjectInputStream(fis);

			// reading object's value and casting to Customer class
			deSerializeCustomer = (Customer) ois.readObject();
			ois.close();

			System.out.println("De-Serialization: Customer object "
					+ "de-serialized from Customer.ser file\n");
		}
		catch (FileNotFoundException fnfex) {
			fnfex.printStackTrace();
		}
		catch (IOException ioex) {
			ioex.printStackTrace();
		}
		catch (ClassNotFoundException ccex) {
			ccex.printStackTrace();
		}

		// printing customer object to console using toString() method
		System.out.println("Printing customer values from "
				+ "de-serialized object... \n" + deSerializeCustomer);
	}
}

Output:

Serialization: Customer object saved to Customer.ser file

De-Serialization: Customer object de-serialized from Customer.ser file

Printing customer values from de-serialized object...
Customer [customerId=102, customerName=SR, customerAge=17]

2.1 ObjectOutputStream and ObjectInputStream:

  • ObjectOutputStream: An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream
  • ObjectInputStream: An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream
  • ObjectOutputStream and ObjectInputStream can provide an application with persistent storage for graphs of objects when used with FileOutputStream and FileInputStream respectively

3. Important points about Serialization and De-Serialization:

  • A java object can be persisted into File storage only if its corresponding class implements java.io.Serializable interface
  • Though java.io.Serializable is a Marker interface which contains no body (i.e.; no methods)
  • But at run time JVM provides special capability to serialize an Object
  • Using writeObject(Object) method of ObjectOutputStream, we can persist Object’s state to file storage
  • And similarly using readObject() method of ObjectInputStream, we can read/restore Object’s state into Java heap memory from persistent storage (like file)
  • If class doesn’t implement java.io.Serializable interface and still if we try to serialize an Object, then program compiles successfully
  • But during program execution JVM throws unchecked exception stating NotSerializableException at run-time

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Transient keyword with Serialization
Java - Serialization and De-Serialization