Complete guide to serialization in java

Arpit Mandliya
Javarevisited
Published in
7 min readDec 16, 2019

Java provides mechanism called serialization to persists java objects in a form of ordered or sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object.

So if we need to serialize any object then it can be read and deserialize it using object’s type and other information so we can retrieve original object.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.
ObjectOutputStream has many method for serializing object but commonly used method is

Similarly ObjectInputStream has

Need of Serialization in java?

Serialization is usually used when there is need to send your data over network or to store in files. By data I mean objects and not text.

Now the problem is your Network infrastructure and your Hard disk are hardware components that understand bits and bytes but not Java objects.

Serialization is the translation of Java object’s values/states to bytes to send it over network or to save it.On other hand,Deserialization is conversion of byte code to corresponding java objects.

Concept of serialVersionUID :

serialVersionUID is used to ensure that same class(That was used during Serialization) is loaded during Deserialization.serialVersionUID is used for version control of object.You can read more at serialVersionUID in java serialization

For Serialization in java:
steps are :

Lets take an example:
Create Employee.java in src->org.arpit.javapostsforlearning

  1. Employee.java
As you can see above,if you want to serialize any class then it must implement Serializable interface which is marker interface. 
Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface
Create SerializeMain.java in src->org.arpit.javapostsforlearning

2.SerializeMain.java

For Deserialization:

Steps are:

Create DeserializeMain.java in src->org.arpit.javapostsforlearning

3.DeserializeMain.java

4.Run it:

First run SerializeMain.java then DeserializeMain.java and you will get following output:

Deserialized Employee...
Emp id: 101
Name: Arpit
Department: CS

So we have serialize an employee object and then deserialized it.It seems very simple but it can be very complex when reference object,inheritance come into the picture.So we will see different cases one by one and how we can apply serialization in different scenarios.

Case 1-What if an object has a reference to other objects

We have seen very simple case of serialization,now what if it also a reference to other objects.

How will it serialized then? will reference object will also get serialized?.

Yes,You don’t have to explicitly serialize reference objects.When you serialize any object and if it contain any other object reference then Java serialization serialize that object’s entire object graph.

For example:Lets say,Employee now has reference to address object and Address can have reference to some other object(e.g.Home) then when you serialize Employee object all other reference objects such as address and home will be automatically serialized. Lets create Address class and add object of Address as a reference to above employee class.

Employee.java:

Create Address.java in org.arpit.javapostsforlearning
Address.java:

Create SerializeDeserializeMain.java in org.arpit.javapostsforlearning

SerializeDeserializeMain.java:

Run it :

When you run SerializeDeserializeMain.java.You will get following output

java.io.NotSerializableException: org.arpit.javapostsforlearning.Address
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)

We got exception what went wrong.I forgot to mention,Address class must also be serializable.So you have to make Address serializable by implement serialzable interface.

Address.java:

Run again:

When you run again SerializeDeserializeMain.java.You will get following output

Deserialized Employee...
Emp id: 101
Name: Arpit
Department: CS
City :Pune

Case 2:What if you don’t have access to reference object’s source code(e.g you don’t have access to above Address class)
If you don’t have access to address class then how will you implement serializable interface in Address class.Is there any alternative to that? yes there is,You can create another class which extends address and make it serialzable but It can fails in many cases:

  • What if class is declared as final
  • What if class have reference to other non serializable object.

So then how will you serialize Employee object? so solution is you can make it transient.If you don’t want to serialize any field then make it transient.

transient Address address

So after making address transient in Employee class when you run program.You will get nullPointerException because during deserialization address reference will be null

Case 3:What if you still want to save state of reference object(e.g above address object):

If you make address transient then during deserialization it will return null.But what if you still want to have same state as when you have serialized address object.Java serialization provides a mechanism such that if you have private methods with particular signature then they will get called during serialization and deserialization so if we provide writeObject and readObject method of employee class and they will be called during serialization and deserialization of Employee object.

Employee.java:

One thing should be kept in mind that ObjectInputStream should read data in same sequence in which we have written data to ObjectOutputStream.
Create Address.java in org.arpit.javapostsforlearning
Address.java:

Create SerializeDeserializeMain.java in org.arpit.javapostsforlearning

SerializeDeserializeMain.java:

Run it :

When you run SerializeDeserializeMain.java.You will get following output

Deserialized Employee...
Emp id: 101
Name: Arpit
Department: CS
City :Pune

so now we got same state of address object as it was before serialization.

Inheritance in Serialization in java:

Now we will see how inheritance affects serialization.So there can be muliple cases whether super class is serializable or not.If not then how will you handle that and how it works.

Lets see by example.
We will create Person.java which will be superclass of Employee.

Case 4: What if superclass is Serializable?
If superclass is serialzable then all its subclasses are automatically serializable.

Case 5:What if superclass is not Serializable?
If super class is not serializable then we have to handle it quite differently.

  • If superclass is not serializable then it must have no argument constructor.

Person.java

Create Employee.java in org.arpit.javapostsforlearning
Employee.java:

Create SerializeDeserializeMain.java in org.arpit.javapostsforlearning

SerializeDeserializeMain.java:

Run it :

When you run SerializeDeserializeMain.java.You will get following output

If superclass is not Serializable then all values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process. so here name is inherited from person so during deserialization,name is initialized to default.

Case 6-What if superclass is Serializable but you don’t want subclass to be Serializable
If you don’t want subclass to be Serializable then you need to implement writeObject() and readObject() method in subclass and need to throw NotSerializableException from these methods.

Case 7-Can you Serialize static variables?
No, you can’t. As you know static variable is at a class level not at the object level and you serialize an object so you can’t serialize static variables.

Externalizable interface can be used in place of serializable if you want more control over serialization. You can read more about it at Externalizable in java

Java Serialization Tutorial:

Summary:

  • Serialization in java is the translation of your Java object’s values/states to bytes to send it over network or save it.On other hand,Deserialization is conversion of byte code to corresponding java objects.
  • Good thing about Serialization is entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.
  • If you want to serialize any class then it must implement Serializable interface which is marker interface.
  • Marker interface in Java is interface with no field or methods or in simple word empty interface in java is called marker interface
  • serialVersionUID is used to ensure that same object(That was used during Serialization) is loaded during Deserialization.serialVersionUID is used for version control of object.
  • When you serialize any object and if it contain any other object reference then Java serialization serialize that object’s entire object graph.
  • If you don’t want to serialize any field,then make it transient.
  • If superclass is Serializable then its subclasses are automatically Serializable.
  • If superclass is not Serializable then all values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process.
  • If you don’t want subclass to serializable then you need to implement writeObject() and readObject() method and need to throw NotSerializableException from this methods.
  • You can’t serialize static variables.

You may also like:

That’s all about Serialization in java.

--

--