Get Upto 50% Offer | OFFER ENDING IN: 0 D 0 H 0 M 0 S

Log In to start Learning

Login via

  • Home
  • Blog
  • What is the Java Serializat...
Post By Admin Last Updated At 2021-03-02
What is the Java Serialization process?

In the terms of computing, Serialization is a process of converting or translating an object or data structure into a byte stream. This is for storing the object or the transmit into a secured place like a file, memory, or database. Moreover, the aim of this process is to store the object’s state in order to rebuild the same upon requirement. Deserialization is quite opposite process of this. Java Serialization refers to the process that allows you to translate an object into a byte stream. This is stored within a file or database to reuse in the future. 

Here, the byte stream is built, platform-independent. Java language is also platform-independent so the serialization process is easier. This means, in the process, Java Serialization, if we serialize an object on one platform then we can deserialize it on another platform.

How Java serialization works internally

As we have seen in the above para that Java Serialization is nothing but a process of converting an object. This conversion is into a byte stream to store the object within a file/DB for later usage. As the process looks easier it also comes with some integrity problems which we can discuss further. 

The purpose of Java Serialization is basically for -

  • Storing the data/info into a disk/file in a way object-oriented
  • Saving the current state of the object
  • Forwarding the data over the network/internet in the object form.

Let us go deeper in this point to learn more about serialization in Java of an object. Moreover, the usage of the serializable interface becomes important here.

Furthermore, we must apply a serializable interface java.io.Serializable to serialize a Java object. 

Here, the “Object Output Stream” class includes the writeObject() method for Object serialization Java. The syntax for this process is as follows:-

public ObjectOutputStream (OutputStream out) throws IOException {}

Another example of this process is-

public final void writeObject(Object obj)

 throws IOException ()

Similarly, the “Object Input Stream” class includes the readObject() method for the deserialization of an object.

Hence, the Object OutputStream class is useful to write antique data types, and the Java objects to an Output Stream. Here, the objects that support the interface serializable only can be written to these streams.

The term “Serializable” refers to a marker interface (having no data member & method) useful to "mark" Java classes. This helps the objects of these classes to get a certain capability. There are two examples of marker interfaces as Cloneable and Remote.

Also, it must be applied by the class whose object a user wants to preserve.

Hence, the “String class” and all the wrapper classes apply the java.io.Serializable interface as a default.

Java serialization

To know more about the serialization process in Java and other things in real-time, get into the Core Java Online Course with OnlineITGuru. Learn practical usage of Java scripts with industry experts.

Java Serialization example

In the following example, we will try to serialize the object of the “Employee” class. Here, the writeObject() method of the “Object Output Stream” class offers the functionality for object serialization in Java. Hence, we are going to save the object’s status within the file name “f.txt”. Let us see this example syntax below- 

import java.io.*;  

class Persist{  

 public static void main(String args()){  

  try{   

  Employee s1 =new Employee(301,"Sasi");   

  FileOutputStream file out = new FileOutputStream("f.txt");  

  ObjectOutputStream out = new ObjectOutputStream(file out);  

  out.writeObject(s1);  

  out.flush();  

  out.close();  

  System.out.println("successful");  

  }catch(Exception e){System.out.println(e);}  

 }  

}  

The output for the above example will be-

Successful 

Furthermore, there are many other examples of Java Serialization such as with inheritance, aggregation, static data member, with arrays or collections, etc. These methods and examples of this process we can see in detail further.

||{"title":"Master in Core Java", "subTitle":"Core Java Certification Training by ITGURU's", "btnTitle":"View Details","url":"https://onlineitguru.com/core-java-online-training-placement.html","boxType":"demo","videoId":"Vi7pdpk5Vq0"}||

Methods of Java Serialization

Here are the different methods useful under the serialization in Java language and their uses. 

writeObject (Object Output Stream)

The presence of this method in the class explains that OOS writeObject() will use it to write the objects to stream. This is commonly useful to hide object variables for integrity maintenance.

readObject (Object Input Stream)

The method readObject() Object Input Stream (OIS) is present in the class that means it allows reading the object from the stream.

Object writeReplace ()

In the presence of this method, the object writeReplace method is called after serialization process. Then the returned object is serialized to the stream with the help of this method.

Object readResolve ()

This method is useful after the deserialization of the process. It is called then to return the final object to the caller program that applies the Singleton pattern using the serialized objects.

Hence, these methods are applied privately so that subclasses cannot be overridden. All these methods are helpful in serialization only and the private use makes them secure.

There are some other methods for Java Serialization as given above. Here we will discuss them in detail with some examples.

Java Serialization with Inheritance

Sometimes we have to do a class extension that doesn’t apply a serializable interface (SI). Moreover, if the class applies those interfaces then the remaining subclasses will also get serializable. The example for this method is as follows;-

import java.io.Serializable; 

class People applies Serializable{ 

 int id; 

 String name; 

 People(int id, String name) { 

  this.id = id; 

  this.name = name; 

 } 

class Employee extends People{ 

 String job; 

 int sal; 

 public Employee (int id, String name, String job, int sal) { 

  super (id, name); 

  this.job=job; 

  this.sal=sal; 

 } 

 

Using this method, you can serialize the Employee class object that extends the people class that is serializable. In this case, the main class or parent class properties are inherited or taken over to subclasses. Thus, if the main class serializes then the subclass also gets serialize.

Java Serialization with Aggregation

In the aggregation method, if a class includes a reference to another class, then all these references must be serializable. If there is the absence of this process, the Java serialization process cannot be executed. Here, exception syntax NotSerializableException is thrown at the runtime.

The following syntax will explain the above process in detail,

class Address{ 

 String addressLine,city,state; 

 public Aaddress(pvt addressLine, pvt city, pvt state) { 

  this.addressLine=addressLine; 

  this.city=city; 

  this.state=state; 

 } 

import java.io.Serializable; 

public class Emp implements Serializable{ 

 int id; 

 String name; 

 Address address;

 public Emp (pvt int id, pvt String name) { 

  this.id = id; 

  this.name = name; 

 }         

Hence, in the above example syntax, the “Address” class is not Serializable. So, we cannot serialize the instance Employee class here.

Java Serialization using static data member

In this case, if there any static data member exists within a class, then it cannot be serialized. Here, the static member is a class and not the part of an object.

The example here, in this case, is as follows;-

class Student applies Serializable{ 

 int id; 

 String name; 

 static String class="Class IV";

 public Employee(int id, String name) { 

  this.id = id; 

  this.name = name; 

 } 

In the case of Java Serialization using array or collection of data, there all objects within array or collection must be serializable. Further, if there is any obstacle in serialization or the object is incapable to serialize, then the process stops.

Java Serialization- Externalizable interface

This new interface offers the space for writing the object’s status into a byte stream that too in a compressed format. Moreover, it is different from the marker interface. Further, there are two different methods that EI Interface provides-

(ObjectOutput out)

(ObjectInput In)

And both throw the IOException.

Transient keyword in Java

The transient keyword is very useful in Java Serialization. If the user is not interested to serialize any data member of any class, then he can mark it as transient. The term “Transient” refers to temporary or short-term.

For instance, there is a class declared as a student with data members’ id, name, and age. In this case, the “id” that the user uses as a string within example syntax, will not get serialized. Thus, after the deserialization of an object that the user performs, he won’t get any id value. Hence, it returns the default value only.

||{"title":"Master in Core Java", "subTitle":"Core Java Certification Training by ITGURU's", "btnTitle":"View Details","url":"https://onlineitguru.com/core-java-online-training-placement.html","boxType":"reg"}||

SerialVersionUID in Java Serialization

In the Java serialization process at runtime, it relates an id with each Serializable class. This has another name “SerialVersionUID”. The version UID is a unique ID given to each object. Also, each and every class that applies the process gets a unique serial version ID. It is useful in verifying the sender and receiver of the serialized object within a class as they loading the same or not. Moreover, here the two persons, the sender & receiver must be the same.

Hence, we use “SerialVersionUID” to verify the same. Also, both the person must have the same SerialVersionUID, otherwise, “InvalidClassException” will be thrown when the user deserializes the object. The users also can declare their own Serial VersionUID within the Serializable class. For this, he must need to build a field Serial VersionUID and allocate a value to the same. The value must be of the long type including static and final. Further, there is an option to declare the value explicitly or can have it private also.

There are some important rules to declare UID here. Such as-

  • The ID should be of the long type and it should be the final and static too.
  • There are no limitations in accessing the variable specifically so we can use anyone for the process.

In case, the user does not allow or explicitly specify a UID, then JVM itself allots one. Although, the general access specifier useful for the Version UID is a private one. Hence, it’s a non-inheritable object.

Advantages of Java Serialization

There are many useful advantages of Java Serialization. Such as-

  • The process enables us to convert or transfer any object using a network by changing it to a byte stream.
  • This is an in-built Java feature so there is no need for any third-party services in this process.
  • It helps us to secure the object’s state and is easy to understand.
  • The programmer can customize it as per the requirement so it is flexible. Hence, they should aware of this process.
  • Here, the process ‘Serialization’ saves much time. The deserialization process takes a little time to build an object than the real object built from class.
  • Mots technologies that we use in our daily business rely on this process.
  • It is useful in cloning the object with the help of this process into a byte stream and then de-serializes the same.
  • The process enables Java to execute authentication, encryption, and compression processes to make Java computing a secure one.
  • Moreover, Java Serialization helps us to apply tenacity in the program by storing the object directly within DB. This too in the form of byte streams and we can easily recover the data whenever we need it.
Disadvantages of Java Serialization
  • There are a few disadvantages also available with this process. They are-
  • Sometimes, the objects that we convert into byte streams do not transfer completely. This leads to errors within the process.
  • In memory utilization, the serialization process becomes inefficient.
  • To use the apps with concurrent access, the serialization process is not useful. There is no control of transition for this.
  • Also, it doesn’t allow good control while object access.
Points to remember in Java Serialization
  • All the related objects must apply the Serializable interface (SI) in the process.
  • We have the option to save the non-static data members using that interface (SI).
  • Hence, the child class or subclass doesn’t need to apply the SI interface in case the main class already done so.
  • Further, the SI interface doesn’t store or save the values of non-static data types or even transient data types.
  • While deserializing an object, the object constructor must not be called.

Thus, these are a few important points that must need to keep in mind applying such a process.

Final Words

I hope you got the idea of what is serialization in the Java programming language and its usefulness. Also, we have seen a little bit of the deserialization process and its application. The process is useful in converting objects into various byte streams as we learned in the above discussion. The best practice to use the Serialization process is that all processes should have the “.ser” extension. By default, it does not cover the static or transient fields. Also, it is to remember that extendable classes serialization is not important to perform unless requiring.

So, this is all for now and to get more information in this regard, go through the Core Java Online Training with ITGuru. This can help you to get more updates on the Serialization process in real-time with expert knowledge.