> For the complete documentation index, see [llms.txt](https://wisdom.gitbook.io/gyan/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wisdom.gitbook.io/gyan/java/interview-questions/serialization.md).

# Serialization

### &#x20;What is Serialization?&#x20;

* 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 ?&#x20;

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

### 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.&#x20;

### 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&#x20;

### What is an Externalizable interface ?

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

### 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();&#x20;
* 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 ?&#x20;

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

### What will be value of transient variables after de-serialization ?&#x20;

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

### &#x20;What are the conditions to meet to serialize an object in Java?

For a class to be serialized successfully, two conditions must be met:&#x20;

* 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.&#x20;

### Which elements of a class are ignored during serialization ?&#x20;

* 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 ?&#x20;

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

### Can we serialize final variables ?&#x20;

**Yes**

### What one should take care of, while serializing the object?&#x20;

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.&#x20;

### What is serialVersionUID ?&#x20;

* 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&#x20;

### 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()&#x20;

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

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?&#x20;

* 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)?&#x20;

* If superclass has implemented Serializable - constructor is not called during DeSerialization process.
* If superclass has not implemented Serializable - constructor is called during DeSerialization process&#x20;

### 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?

&#x20;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?&#x20;

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?

&#x20;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.&#x20;

### What happens if the object to be serialized includes the references to other serializable objects?&#x20;

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?&#x20;

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&#x20;

### What is the difference between writeObject() and defaultWriteObject() method in serialization ?&#x20;

* 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.&#x20;

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

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