Serialization

What is Serialization?

  • A mechanism, where an object can be represented as a sequence of bytes .

  • Serialized object (byte stream) can be transferred over network, persisted/saved into file, persisted/saved into database.

  • Java provides Serialization API for serializing and deserializing object, which includes java.io.Serializable, java.io.Externalizable, ObjectInputStream and ObjectOutputStream etc.

Why do we need serialization ?

Serialization is usually used when the need arises to send your data over network or stored in files.

How to implement serialization in java ?

Java provides Serialization API for serializing and deserializing object which includes java.io.Serializable, java.io.Externalizable, ObjectInputStream and ObjectOutputStream etc.

What is Serializable interface?

It is a marker interface having no methods indicates to jvm that the implemented class will be used in serialization process

What is an Externalizable interface ?

Externalizable interface is used to write the state of an object into a byte stream in compressed format.

What is the use of Externalizable interface in Java ?

  • Externalizable interface allows to write/code custom logic for both serialization & de-serialization

  • It has 2 methods namely writeExternal(); & readExternal();

  • Use writeExternal(); method to code/write custom serialization logic

  • Use readExternal(); method for custom de-serialization process.

Difference between serializable and Externalizable or When will you use Serializable or Externalizable interface? and why?

Serializable

Externalizable

It is marker interface. You don’t have to provide implementation of any method

Externalizable is not marker interface, you have to override writeExternal() and readExternal() method.

Serializable interface has less control over serialization process and it is optional to override readObject and writeObject.

Externalizable interface has more control over serialization process and it is mandatory to override writeExternal and readExternal.

JVM uses reflection to perform serialization in the case of Serializable interface which is quite slow

Programmer have to implement readExternal and writeExternal methods but it relatively results in better performance

In case you have small objects where all attributes are required to be serialized then its good using Serializable interface and use of transient variable as appropriate.

Externalizable interface can be really effective in cases when you have to serialize only some dynamically selected attributes of a large object

Default constructor is not called during Deserialization process.

Default constructor is called during Deserialization process.

What is Deserialization? How to do it?

  • The process of reading a state of an Object from a file is called DeSerialization.

  • But practically, it is the process of converting & re-storing Java Object’s state into heap memory from file supported form (which is in binary format)

What is transient keyword ?

Transient keyword is used to prevent a variable to take part in serialization process .

What will be value of transient variables after de-serialization ?

After de-serialization transient variables will have default values Like, 0 for int data-type, null for String, false for Boolean data-type, etc.

What are the conditions to meet to serialize an object in Java?

For a class to be serialized successfully, two conditions must be met:

  • The class must implement the java.io.Serializable interface.

  • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Which elements of a class are ignored during serialization ?

  • Objects are serialized and not classes and hence Static variables are ignored.

  • Transient is an explicit declaration to ignore the variable during serialization and hence transient instance variables are ignored too.

  • Base class instance variables if the base class hasn't been declared serializable.

Can we serialize static variables ?

No, Only Object and its members are serialized. Static variables are shared variables and doesn't correspond to a specific object.

Can we serialize final variables ?

Yes

What one should take care of, while serializing the object?

One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializable Exception.

What is serialVersionUID ?

  • serialVersionUID is used to ensure that same class(That was used during Serialization) is loaded during Deserialization.

  • Everytime an object is serialized the java serialization mechanism automatically computes a hash value by passing the meta information for the class.

  • This id is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.

  • serialVersionUID must be Static and final. You can assign any number to it

Serialization and deserialization of singleton class.

The problem with serialized singleton class is that whenever we deserialize it, it will create a new instance of the class. To overcome this scenario all we need to do is to provide the implementation of readResolve() method.

How to avoid cloning, serialization in the singleton class ?

Override Object.clone() and throw exception Cloning-exception, For deserialization- read.resolve()

Can you give me a use case where you utilized serialization in your project code? Or Real time example .

we use serialization when we send response to client in JSON format.(the process of converting model object into json is nothing but serialization

Can we serialize objects with only private variables in Java ?

  • It depends on how we are serializing. The Serialization API doesn't worry about private variables and convert it into binary representation.

  • If we are using a library to map it to JSON / XML using XML Mappers, it may create trouble.

Is constructor of class called during DeSerialization process?

  • If Serializable has been implemented - constructor is not called during DeSerialization process.

  • if Externalizable has been implemented - constructor is called during DeSerialization process.

Is constructor of super class called during DeSerialization process of subclass (Important)?

  • If superclass has implemented Serializable - constructor is not called during DeSerialization process.

  • If superclass has not implemented Serializable - constructor is called during DeSerialization process

Other than Serialization what are the different approach to make object Serializable?

Besides the Serializable interface, at least three alternate approaches can serialize Java objects:

  • Using Externalizable interface, which extends Serializable. By implementing Externalizable, a developer is responsible for implementing the writeExternal() and readExternal() methods.

  • Using XML serialization is an often-used approach for data interchange.

  • Using own serialization approach one can write an object's content directly via either the ObjectOutputStream or the DataOutputStream

To serialize an array or a collection all the members of it must be serializable. True /False?

True, because by default every collection implement serializable interface.

While serializing you want some of the members not to serialize, how do you achieve it?

If you don't want any field to be part of object's state then declare it either static or transient .

What will be the value of transient variable after de-serialization?

It’s default value. e.g. if the transient variable in question is an int, it’s value after deserialization will be zero. And Integer will be assign to null.

A If a class is serializable but its superclass in not, what will be the state of the instance variables inherited from super class after deserialization?

If parent class doesn’t implement the Serializable interface, then its state won’t transform into a byte stream while serializing the child class instance. The values of the instance variables inherited from superclass will be reset to the values they were given during the object construction.

What happens if an object is serializable but it includes a reference to a non-serializable object?

If you try to serialize an object of a class which implements serializable, but the object includes a reference to an non-serializable class then a NotSerializableException will be thrown at runtime.

What happens if the object to be serialized includes the references to other serializable objects?

Then other object’s state also will be saved as the part of the serialized state of the object .

Can you Customize Serialization process or can you override default Serialization process in Java?

Yes by overriding ObjectOutputStream.writeObject (saveThisobject) and for reading object ObjectInputStream.readObject()

  • To customize serialization process, instead of implementing Serializable interface implement java.io.Externalizable interface which has 2 methods.

  • These methods are writeExternal(); & readExternal();

  • To serialize, use writeExternal(); method and write custom logic Similarly, to de-serialize use readExternal(); method and code custom logic

What is the difference between writeObject() and defaultWriteObject() method in serialization ?

  • writeObject() is the most common method used to serialize the instance of class.

  • defaultWriteObject() method we use in custom or overridden writeObject method to do default processing of serialization.

  • When you call writeObject() method it doesn’t serialize the instances which are declared transient. So defaultWriteObject method is needed to customize the default serialization process.

Suppose super class of a new class implement Serializable interface, how can you avoid new class to being serialized?

To avoid Java serialization you need to implement writeObject() and readObject() method in your Class and need to throw NotSerializableException from those method.

Last updated