Java ProgrammingLearn How to serialize and deserialize objects in Java

Learn How to serialize and deserialize objects in Java

Learn-How-to-serialize-and-deserialize-objects-in-Java
One of the fundamental strength of Java is its serialization mechanism. This is basically serialization of Java objects, where the object is persisted as a sequence of bytes. The persistent storage can be file system, database or streams. And, deserialization is just the reverse process, where the sequences of bytes are again converted back into objects. The important point to note is that the object is stored in its current state and reversed back to that state only.
In this article, we will try to explore the core concepts of Java object serialization and also work on some coding examples.

Why we need serialization?
Everything in Java is represented as objects. So, in a Java application, be it stand-alone, enterprise or in some other form, you need to deal with objects. These objects are having their own states (states are nothing but the value or data it contains at any point of time) and it varies from time to time.

In an application, if we need to store data, we can store it in a database or file system (in the form of files). And, then retrieve it whenever required. But, this is typically handling and storing the raw data.

Now, if we need to store an object (with its current state and value) we cannot use database or file system directly. Because they do not understand object, so, we need to store it in the form of bytes. This mechanism is also applicable when we need to transfer an object over network.

But, the question is – ‘How do we perform this task’? Serialization is the solution to this problem. It can also be defined as a protocol, which can be used by any party to serialize or de-serialize an object.

Following are the two most important purpose for which serialization is widely used.

  • Persists objects in storage (Database, file system, stream)
  • Transfer Objects over network

Some related concepts
Before moving into the next sections on serialization mechanisms and code samples, we must understand some basic technical concepts used in the serialization process.

serialVersionUID: This is basically the identification of a serialized object. It is used to ensure that the serialized and de-serialized objects are same. Sometime this UID is also used for refactoring purpose. More details can be found here.

Marker Interface: To implement serialization in Java or making an object serializable, you need to implement Serializable interface. Serializable is a marker interface, which means it is an interface without any fields and methods, for implementing some special behaviour. There are also other marker interfaces available in Java.

Transient Keyword: This is a very important keyword in Java. There may be a need to store a part of an object and avoid some fields which may contain sensitive information like credit card number, password etc. Here, we just need to define those fields as ‘transient’, and it will not allow those fields to be saved during the serialization process.

Object Stream classes: Two object stream classes are very important for serialization and de-serialization process. Those are ObjectOutputStream and ObjectInputStream. We will check the implementation in the following code sample section.

How serialization works – Some code Examples
In this coding example we will have three Java classes as mentioned below.

  • java class representing the object to be serialized
  • java class for serializing Student object
  • java class to extract the values from the saved Student object

Following is the Student class with some relevant fields. Please note that the ‘pwd’ field is marked as ‘transient’ to avoid saving it as a part of the object. The other fields will be saved as part of the Student object.

Listing1: Student class sample code

public class Student implements java.io.Serializable
{
   public String name;
   public String address;
   public String userId;
   public transient String pwd; 
   public void objectCheck()
   {
      System.out.println("Student details " + name + " " + address +" "+ userId);
   }
}

Now, the 2nd class is designed to serialize Student object as shown below. It creates a Student object and save it in a file named ‘student.ser’ in the local files system.

Listing2: Serializing Student class object

import java.io.*;
public class SerializeExample
{
   public static void main(String [] args)
   {
      Student st = new Student();
      st.name = "Allen";
      st.address = "TX, USA";
      st.userId = "Aln";
      st.pwd = "Aln123$";      
      try
      {
         //Create file output stream
         FileOutputStream fileOutStr =
         new FileOutputStream("student.ser");		 
        //Create object output stream and write object
         ObjectOutputStream objOutStr = new ObjectOutputStream(fileOutStr);
         objOutStr.writeObject(st);
         //Close all streams
         objOutStr.close();
         fileOutStr.close();
         System.out.printf("Serialized data is saved in a file  - student.ser");
      }catch(IOException exp)
      {
          exp.printStackTrace();
      }
   }
}

Output from this class is shown below.
Image1
Image1: Showing serialization output

The 3rd class is designed to de-serialize the saved Student object and extract the values from it. The extracted values will be shown on the Java console.

Listing3: De-serializing Student object

import java.io.*;
public class DeserializeExample
{
   public static void main(String [] args)
   {
      //Create student object
	  Student st = null;
      try
      {
         FileInputStream fileInStr = new FileInputStream("student.ser");
         ObjectInputStream objInStr = new ObjectInputStream(fileInStr);
         st = (Student) objInStr.readObject();
         objInStr.close();
         fileInStr.close();
      }catch(IOException exp)
      {
         exp.printStackTrace();
         return;
      }catch(ClassNotFoundException cexp)
      {
         System.out.println("Student class not found");
         cexp.printStackTrace();
         return;
      }
      System.out.println("Deserialized Student...");
      System.out.println("Name: " + st.name);
      System.out.println("Address: " + st.address);
      System.out.println("User Id: " + st.userId);
      System.out.println("Password: " + st.pwd);
    }
}

Output from this class is shown below. Please note that the output does not print the value of the password, as it was declared as transient.
Image2
Image2: Showing de-serialization output

Some real life implementations
In this section, let us have a look at some of the real life implementations of serialization. It will help you understand the importance and the usage of object persistence.

  • Think of a game application where the state is very important. Now, when a user left the game at any point of time, the state is serialized and stored in some type of storage. While the user wants to re-start the game again, same state of the object is recreated by the process of de-serialization. So, nothing is lost in the whole process.
  • The other important example is ATM application. When a user request some withdrawal from an ATM machine (which is the client), the request is sent to the server as a serialized object. On the server end, the reverse process (de-serialization) is executed and the action is performed. This is an example of how serialization works over network communication.
  • Stock market update is another example where the update is stored as a serialized object and served to the client whenever required.
  • In any web application, the user session information is very important to maintain. Because, if at any point of time, the application fails or internet does not work, the user is disconnected from the application in the middle of some activity. Now, this half-done activity is stored as a serialized object, and restored when connection is established again. As a result, the user can continue from the same point where he left his activity.

Conclusion:
Java serialization is a very important feature to learn. In this article, we have discussed serialization in details along with its relevant concepts. We have also explained one coding example to show how serialization works. The example can be enhanced or modified to perform addition tasks. Overall, serialization is very flexible in nature, but the developers need to know the tricks and tips to implement it properly. Hope this article will provide you a guidance to move forward.

1 COMMENT

  1. if we have serialize any object then it can be read and deserialize it using object’s type and other information so we can retrieve original object. Many Thanks for sharing this article .

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -