Learn ABC Of Java Serialization With Examples


In this post, we are going to explore an important Java concept frequently asked during Job’s interviews i.e. Java Serialization. We’ll exclusively talk about serialization and will explain its basic to advance level features with the help of code examples and sample project. Besides knowing about serialization in Java and it’s even more important to learn the different ways to implement serialization. We’ve also addressed them in this post. You probably have faced questions like does serialization require versioning or have performance issues? So, read this post through the end, we’ve covered all such questions. First of all, go over this generic definition of serialization.

“It is a way of converting data structures or state of the object in a format that can be preserved and retrieved as and when required. The process of reforming the object from the decomposed state is called deserialization. Today most of the object-oriented languages (including Java) provide native support for serialization and deserialization.”

Now you can see in the next section is the list of most basic Java serialization questions and answers. It’ll surely increase your knowledge of Java serialization topic.

1- Basics Of Java Serialization.

1.1- What Is The Concept Of Java Serialization?

Answer: Java serialization is the process of turning an object into a stream of bytes or byte array. The byte array represents the class of the object, the version of the object, and the internal state of the object.

1.2- What Is Deserialization In Java?

Answer: Deserialization is the process of rebuilding byte stream into a live Java Object that must be usable.

1.3- What Is The Purpose Of Java Serialization?

Answer: You can use Java serialization to perform the following tasks.

1.3.1- Stashing.

Rather holding a large object in memory, it’s better to cache it to a local file via serialization. For your note, if you attempt to save a non-serializable object, the JVM will fail the operation with <NotSerializableException>.

1.3.2- Data Transmission.

Java permits to serialize an object over a network using RMI (Remote Method Invocation), a distributed technology of Java. RMI enables a Java client object communicates with the instance of a Java server hosted on a remote system. For example, an ATM center of your locality can interact with a bank server located in a different country.

1.3.3- Persistence.

If you want to preserve the state of a particular operation to a database, just serialize it to a byte array, and save to the database for later use.

1.3.4- Deep Cloning.

In Java, it is also known as the deep copy. It causes an object to copy along with the objects to which it refers. You need to write a customized clone class to achieve this. Java serialization can save you the trouble of adding a clone class. Serializing the object into a byte array and then deserializing it to another object will fulfill the purpose.

1.3.5- Cross JVM Communication.

Serialization works the same across different JVMs irrespective of the architectures they are running on.

2- How To Implement Java Serialization?

Java provides out of the box solution to serialize an object. It outlines a set of generic interfaces. Your class needs to implement just one of them to enable serialization. In the next section, we’ll explore these built-in interfaces and some of the ready to use examples. Mainly, we’ll take on the following Java Serialization concepts.

2.1- Implement Java Serialization Using Serializable Interface.

It is the simplest way of enabling Java serialization. If you wish your class to get serialized, just implement the Java Serializable interface. It is a marker interface that doesn’t provide any method or field to implement.

Q-1 What is a marker Interface in Java?

Answer: In Java, marker Interface holds a special place because it has no methods declared in it and the class implementing it needs not to override any method. A marker interface instructs the JVM to process the object suitable for a special task. For instance, the implementation of Serializable interface makes the JVM permit its object to write to a file.

That was a brief summary of Java Serializable Interface. Now we’ll see how to implement the Serializable interface in a Java class and apply serialization.

2.1.1- Java Serialization Example.

We’ll use a basic example for demo purpose. For the sample, you will be creating the following class files as given below.

1- <SerializationDef.java>.
2- <SerializationLib.java>.
3- <SerializationDemo.java>. SerializationDef.Java.

This file defines the Java class that we’ll use for serialization. This class represents a simple Java bean carrying some properties and getter/setter methods. By default, all the properties get serialized. But you can change this behavior. Let’s check out how?

Q-1 What is the use of transient keyword?

Answer: The <transient> is a keyword in Java. It marks a field to exclude from serialization. You can use this keyword for a variable which you don’t want to be the part of the persistent state of an object.

Q-2 Would a static member of the class get serialized?

Answer: No. A static member is associated with the class, not with the object of the class. It gets memory once during the loading of the class. And gets stored in the <PERMGEN> section of the heap.

We’ll explain the above concepts using a sample project. Please follow the parts of the sample project given below.

If you see the below class file, we’ve marked the <FeatureCount> variable as transient. So it will be excluded from being serialized. SerializationLib.Java.
For serialization, you’ll need to copy the object to a file. You may then seek to deserialize it from the same file. For all this, you’ll need helper functions, you can find them in the below code snippet. You’ll notice from the code below that we are using the <ObjectOutputStream> and <ObjectInputStream> classes for serialization. Their methods take the <Object> class variable as the argument which is the parent class of all the classes in Java. SerializationDemo.Java.
Until now we’ve set the basic structure of the serialization sample. Now let’s create the main file to demonstrate the serialization process.

Now we are all done. And it’s time to create a Java project in Eclipse. Add all the above files into the project. Since we’ve fully verified the code, there shouldn’t be any compile error. If you still see any error, please check that JDK path is correctly set in the Eclipse preferences>>Java>>Installed JREs.Finally, when you run the project, it’ll give the following output. From the result, you can check the value of <FeatureCount> was not saved because we declared it as a transient variable.


2.2- Advance Java Serialization With Inheritance.

There occur two cases when we use serialization with inheritance.

1- When parent class implements the Serializable interface, the child class does it automatically.
2- If parent class doesn’t implement the Serializable interface, then its state won’t transform into byte stream while serializing the child class instance.

For managing the 2nd case, you need to implement the following two methods in the Child class.

1- <readObject()>.
2- <writeObject()>.

These methods will help in transforming the parent class state to the stream, serialize it and finally allow retrieving it. Let’s see all of this in action.

2.2.1- Java Serialization Example With Inheritance.

We’ll demonstrate this concept through the below sample project. The first part of the project is the <ParentClass.java> file which doesn’t implement the Serializable interface. ParentClass.Java File. ChildClass.Java File.

Next is the <ChildClass.java> file which defines the read/write object method for preparing the stream of parent class state. For your information, the order of reading/writing data to the byte stream would remain same. Another important point you’ll notice that the child class is implementing the <ObjectInputValidation> interface. It’ll allow overriding of some methods where you can add some business logic to ensure the data integrity. InheritanceDemo.Java File.

Let’s now create a demo class file to serialize/deserialize the child class data including the parent. And see whether we can retrieve the parent class state from the serialized form.

When you execute the above code, you’ll get the following output.


2.3- Learn To Manage Class Refactoring With JavaSerialization.

Java serialization permits to refactor the underlying class. Following is the listof changes that are allowed in a class and won’t disturb the deserializationprocess.

  • You can add new members to the class.
  • Switching of a variable from transient to non-transient is allowed. But Serialization will consider such variables as new.
  • Make a variable from static to non-static. Serialization will count it as a new variable.

However, Java imposes a condition for all these changes to work. You can fulfillit by adding a unique identifier, the <serialVersionUID> in the class to track themodifications under a common tag. By default, serialization will automaticallycompute the <serialVersionUID> by going through all the fields and methods.That’s why if you try to alter any class variable without manually specifying theversion identifier, the JVM will throw the <java.io.InvalidClassExceptio> asit detects a change in the identifier value.

2.3.1- How To Generate A <SerialVersionUID>?


There are three ways you can use to produce a <serialVersionUID> value. Use the <serialver> command.

JDK bundles a tiny command line utility called the <serialver>. You just need to pass the serializable class name as command parameter to get its version identifier.

Before you run the above command, make sure you have set the path to the JDK’s bin folder which contains the above command line tool. Use the Eclipse IDE.

In the Eclipse IDE, hover at the serialization class. It’ll open a context menu and display three options. Choose any of the first two options as given below.

  • Add default serial version ID, or
  • Add generated serial version ID. Assign the value of your choice.

Just pick a number you like and set as a serial version ID. But do postfix the number with an “L”.

2.4- Learn To Use The Java Externalizable Interface For Serialization.

The default serialization method is not secure and has performance issues. You can see the list below to check the performance issues with default serialization.

1- Serialization depends on the recursion mechanism. When serialization of a child class object starts, it triggers the serialization of other instance variables from the chain of parent classes which continues until it reaches the Object class of these variables. It leads to a lot of overheads.
2- While serializing an object class description information is attached to the stream. Lots of data and metadata stretch down the performance.
3- Serialization also needs a serial version ID for tracking class level changes. If you don’t set it manually, serialization calculates it automatically by going through all the fields and methods. More the size of the class more will be the time to calculate the value. So this is again a potential performance issue.
4- We can solve all of the above issues with Externalization interface.

2.4.1- What Is The Externalizable Interface And How Is It Better Than The Serializable Interface?

Answer: Externalization is an extension to the Serializable interface. If you want to externalize an object, then your class needs to implement the Externalizable interface and a default public constructor. In Externalization process, only the identity of the class is added to the serialization stream. And the class is responsible for the storage and retrieval of the instance information. It gives complete control of what to add and what to leave during serialization. The basic serialization doesn’t offer the similar flexibility.

For your information, Externalizable is not a marker interface instead it exposes two methods – writeExternal and readExternal. The target class implements these methods to seize full control over the format and contents of the stream relating to the object and its supertypes. These methods must have the ability to coordinate with the object’s supertypes to save its state. They supersede the tailor-made implementation of <writeObject> and <readObject> methods.

Now it’s time to create an Eclipse sample project to demonstrate the use of Externalizable interface. In this sample project, we’ll add the following two Java class files.

  • UIMap.java, this file defines a class which implements the Externalizable interface and provides the <readExternal()> and <writeExternal()> methods.
  • UIMapDemo.java, this file will create the UIMap object and test the Java serialization process via the Externalizable interface.


2.4.2- Java Externalizable Example.

We are embedding the source code of these files so that you can instantly add it to your local Java project. The first code snippet relates to the <UIMap.java> class file, have a look at the below code. UIMap.Java Class File. UIMapDemo.Java Class File.

Now, see the <UIMapDemo.java> file to test the functionality of the Java serialization using the Externalizable interface.

When we execute the above sample Java project, it’ll generate the following output.


2.4.3- Download Sample Projects.

Now it’s time to download the sample project so that you can easily play around with the Java serialization examples. Please use the below link to start your download.

Download Serialization code samples.





We’ve lately published an interesting quiz on Java serialization concept. And we highly recommend you to attempt this questionnaire. It’ll test your knowledge as well help in establishing your hold on the subject.


Final Thought.

We wish that the A-Z Java tutorial of doing serialization in different ways would have helped you in moving a step further on the Java learning ladder. We wanted to cover the whole Java Serialization topic and the little things around it in a single article. Our goal was to make sure the post should get you almost every detail about Serialization in Java. You can get more specific detail on this topic from the Oracle’s website.

If you liked the way we’ve covered every little detail of the subject, then please use the comment box and share your feedback. Also, please forward this post to your friend circle and on the social media platforms you use.


Master the Basics of Java in Less Than 2 Hours

Master Object Oriented Design in Java – Homework + Solutions

Java In-Depth: Become a Complete Java Engineer! 


Please enter your comment!
Please enter your name here