Serialization and Deserialization in Java

Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies

The reverse operation of serialization is called deserialization where byte-stream is converted into an object. The serialization and deserialization process is platform-independent, it means you can serialize an object in a platform and deserialize in different platform

For serializing the object, we call the writeObject() method ObjectOutputStream, and for deserialization we call the readObject() method of ObjectInputStream class.

We must have to implement the Serializable interface for serializing the object.

Advantages of Java Serialization

It is mainly used to travel object’s state on the network (which is known as marshaling).

Serialization
Serialization

Serializable is a marker interface (has no data member and method). It is used to “mark” Java classes so that the objects of these classes may get a certain capability. The Cloneable and Remote are also marker interfaces

It must be implemented by the class whose object you want to persist

The String class and all the wrapper classes implement the java.io.Serializable interface by default

Example of Serialization

import java.io.Serializable;
 public class Student implements Serializable{
int id;
 String name;
 public Student(int id, String name) {
 this.id = id;
 this.name = name;
 }
 }

In the above example, Student class implements Serializable interface. Now its objects can be converted into stream

ObjectOutputStream class

The ObjectOutputStream class is used to write primitive data types, and Java objects to an OutputStream. Only objects that support the java.io.Serializable interface can be written to streams.

Constructor

1) public ObjectOutputStream(OutputStream out)
throws IOException {}
creates an ObjectOutputStream that writes to the
specified OutputStream
ObjectOutputStream class

Important Methods

MethodDescription
1) public final void writeObject(Object obj) throws
IOException {}
writes the specified object to the
ObjectOutputStream.
2) public void flush() throws IOException {}flushes the current output stream.
3) public void close() throws IOException {}closes the current output stream.
ObjectOutputStream class method

ObjectInputStream class

An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream

Constructor

1) public ObjectInputStream(InputStream in)
throws IOException {}
creates an ObjectInputStream that reads from
the specified InputStream.
ObjectInputStream class

Important Methods

MethodDescription
1) public final Object readObject() throws
IOException, ClassNotFoundException{}
reads an object from the input stream.
2) public void close() throws IOException {}closes ObjectInputStream.
ObjectInputStream class

Example of Java Serialization

In this example, we are going to serialize the object of Student class. The writeObject() method of ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the object in the file named f.txt

import java.io.*;
class Persist{
 public static void main(String args[]){
 try{
 //Creating the object
 Student s1 =new Student(211,"ravi");
 //Creating stream and writing the object
 FileOutputStream fout=new FileOutputStream("f.txt");
 ObjectOutputStream out=new ObjectOutputStream(fout);
 out.writeObject(s1);
out.flush();
 //closing the stream
 out.close();
 System.out.println("success");
}catch(Exception e){System.out.println(e);}
 }
 }

success

Example of Java Deserialization

Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation of serialization. Let’s see an example where we are reading the data from a deserialized object.

import java.io.*;
class Depersist{
public static void main(String args[]){
try{
 //Creating stream to read the object
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
 //printing the data of the serialized object
System.out.println(s.id+" "+s.name);
 //closing the stream
in.close();
 }catch(Exception e){System.out.println(e);}
 }
 }

Java Serialization with Inheritance (IS-A Relationship)

If a class implements serializable then all its sub classes will also be serializable. Let’s see the example given below

import java.io.Serializable;
 class Person implements Serializable{
 int id;
String name;
 Person(int id, String name) {
 this.id = id;
this.name = name;
}
 }
 class Student extends Person{
 String course;
 int fee;
 public Student(int id, String name, String course, int fee) {
 super(id,name);
 this.course=course;
 this.fee=fee;
}
}

Now you can serialize the Student class object that extends the Person class which is Serializable. Parent class properties are inherited to subclasses so if parent class is Serializable, subclass would also be.

Java Serialization with Aggregation (HAS-A Relationship)

If a class has a reference to another class, all the references must be Serializable otherwise serialization process will not be performed. In such case, NotSerializableException is thrown at runtime

class Address{
String addressLine,city,state;
 public Address(String addressLine, String city, String state) {
this.addressLine=addressLine;
 this.city=city;
 this.state=state;
 }
}
 import java.io.Serializable;
public class Student implements Serializable{
 int id;
String name;
Address address;//HAS-A
public Student(int id, String name) {
 this.id = id;
this.name = name;
}
}

Since Address is not Serializable, you can not serialize the instance of Student class.

Note: All the objects within an object must be Serializable

Java Serialization with the static data member

If there is any static data member in a class, it will not be serialized because static is the part of class not object.

class Employee implements Serializable{
 int id;
 String name;
 static String company="SSS IT Pvt Ltd";//it won't be serialized
 public Student(int id, String name) {
 this.id = id;
this.name = name;
}
}

Java Serialization with array or collection

Rule: In case of array or collection, all the objects of array or collection must be serializable. If any object is not serialiizable, serialization will be failed.

Externalizable in java

The Externalizable interface provides the facility of writing the state of an object into a byte stream in compress format. It is not a marker interface.

The Externalizable interface provides two methods:

  • public void writeExternal(ObjectOutput out) throws IOException
  • public void readExternal(ObjectInput in) throws IOException

Java Transient Keyword

If you don’t want to serialize any data member of a class, you can mark it as transient.

class Employee implements Serializable{
 transient int id;
 String name;
 public Student(int id, String name) {
 this.id = id;
 this.name = name;
 }
}

Now, id will not be serialized, so when you deserialize the object after serialization, you will not get the value of id. It will return default value always. In such case, it will return 0 because the data type of id is an integer.

SerialVersionUID

The serialization process at runtime associates an id with each Serializable class which is known as SerialVersionUID. It is used to verify the sender and receiver of the serialized object. The sender and receiver must be the same. To verify it, SerialVersionUID is used. The sender and receiver must have the same SerialVersionUID, otherwise, InvalidClassException will be thrown when you deserialize the object. We can also declare our own SerialVersionUID in the Serializable class. To do so, you need to create a field SerialVersionUID and assign a value to it. It must be of the long type with static and final. It is suggested to explicitly declare the serialVersionUID field in the class and have it private also.

For example:

private static final long serialVersionUID=1L;

import java.io.Serializable;
 class Employee implements Serializable{
 private static final long serialVersionUID=1L;
 int id;
 String name;
 public Student(int id, String name) {
 this.id = id;
 this.name = name;
 }
 }

SerializationDemo

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);
oos.writeObject(object1);
oos.flush();
oos.close();
}
catch(IOException e) {
System.out.println("Exception during serialization: " + e);
System.exit(0);
}
// Object deserialization
try {
MyClass object2;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
object2 = (MyClass)ois.readObject();
ois.close();
System.out.println("object2: " + object2);
}
catch(Exception e) {
System.out.println("Exception during deserialization: " + e);
System.exit(0);
}
}
}
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;
}
}

Output of this programme

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

Leave a Comment