Serialization in java

This is 1st part of java Serialization tutorial.

Java Serialization Tutorial:

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 a 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:

So we have serialized 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 a very simple case of serialization, now what if it also a reference to other objects.

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

Yes,You don’t have to explicitly serialize reference objects. When you serialize any object and if it contains any other object reference then Java serialization serializes 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. Let’s create Address class and add object of Address as a reference to the 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

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

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.

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 the same state as when you have serialized address object.Java serialization provides a mechanism such that if you have private methods with a 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

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.

Let’s 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 serializable then you need to implement writeObject() and readObject() method and need to throw NotSerializableException from these methods.

Case 7-Can you Serialize static variables?
No, you can’t. As you know static variables are at class level not at 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

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 these methods.
  • You can’t serialize static variables.

That’s all about Serialization in java.

Related Posts

  • Serialization interview questions
    14 February

    Java Serialization interview questions and answers

    Serialization is one of most important concept in java. If you are going to face core java interview, then you might be asked some questions from Serialization. Java Serialization Tutorial: Serialization in java Java Serialization interview questions and answers serialversionuid in java serialization externalizable in java Transient keyword in java Difference between Serializable and Externalizable […]

  • 14 February

    Difference between Serializable and Externalizable in Java

    In this tutorial,  we are going to see differences between Serializable and Externalizable interface in Java. Java Serialization Tutorial: Serialization in java Java Serialization interview questions and answers serialversionuid in java serialization externalizable in java Transient keyword in java Difference between Serializable and Externalizable in Java Before understanding difference, let me provide a short note on Serializable […]

  • 19 May

    Java transient keyword with example

    Transient variable is the variable whose value is not serialized during serialization. You will get default value for these variable when you deserialize it. Lets say you have Country class and you don’t want to Serialize population attribute as it will change with time, so you can declare population attribute as transient and it won’t […]

  • 26 February

    Externalizable in java

    This is 3rd part of java Serialization tutorial Java Serialization Tutorial: Serialization in java Java Serialization interview questions and answers serialversionuid in java serializationexternalizable in java Transient keyword in java Difference between Serializable and Externalizable in Java Before understanding Externalizable interface, you need to have idea about Serialization.You can read more about Serialization at Serialization […]

  • 11 March

    serialVersionUID in java Serialization

    This is 2nd part of java Serialization tutorial Java Serialization Tutorial: Serialization in java Java Serialization interview questions and answers serialversionuid in java serialization externalizable in java Transient keyword in java Difference between Serializable and Externalizable in Java serialVersionUID is used to ensure that same class(That was used during Serialization) is loaded during Deserialization.serialVersionUID is […]

Comments

  1. Don't you think you should provide serialVersionUID in the class' in your example. IMHO always have an serialVersionUID in class' who implements Serializable.

    1. Hello Harsh,
      Yes you are right.I forgot to do so.Thanks for your suggestion.I have updated article

  2. How can we serialize an object have non serialize property which is not accessible by us,because that property is coming from service.i.e. some Enum used by sevice and we are unable to serilize the same though my object implemts serilizable interface.

    Please suggest.

  3. Hi, am new to JAVA World and I have read many posts and articles regarding the serialization in java, but get understand after reading this post.. Can you please post some more topics related to CORE JAVA (i.e OOPS Concepts, multithreading , Synchronization)…

    If so , then it would be very helpful to me as well as to others…

    Thank you…

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.