Serialization Interview Questions:-
1. What is Serialization in Java ?
Object Serialization in Java is a process used to
convert Object into a binary format which can be persisted into disk
or sent over network to any other running Java virtual machine; the
reverse process of creating object from binary stream is called
deserialization in Java.
Java Serialization is one of important concept but
it's been rarely used as persistence solution and developer mostly
overlooked Java serialization API.
As per my experience Java Serialization is quite an
important topic in any core Java interview, In almost all the
interview I have faced there are one or two Java serialization
questions and I have seen an interview where after few question on
serialization candidate start feeling uncomfortable because of lack of
experience in this area.
2. What is the need of Serialization?
The serialization is used :-
(a). To send state of one or more object's state over the network through a socket.
(b). To save the state of an object in a file
(c). An object's state needs to be manipulated as a stream of bytes.
3. What is serialVersionUID? What would happen if you don't define this?
SerialVersionUID is an ID which is stamped on object when it get serialized usually hashcode of object, you can use tool serialver to see serialVersionUID of a serialized object .
SerialVersionUID is used for version control of object. you can specify serialVersionUID in your class file also.
Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch, to learn more about serialversionuid see this article.
4. Do we need to implement any method of Serializable interface to make an object serializable?
No. Serializable is a Marker Interface. It does not have any methods.
5. What happens if the object to be serialized includes the references to other serializable objects?
If the object to be serialized includes references to the other objects, then all those object's state also will be saved as the part of the serialized state of the object in question. The whole object graph of the object to be serialized will be saved during serialization automatically provided all the objects included in the object's graph are serializable.
6. What is a transient variable?
These variables are not included in the process of serialization and are not the part of the object's serialized state.
7. Are the static variables saved as the part of serialization?
No. The static variables belong to the class are not the part of the state of the object so they are not saved as the part of serialized object.
8. Difference between Externalizable and Serialization interface (Important)?
(a). It is a marker interface it doesn't have any method.
(b). Serializable provides its own default serialization process, we just need to implement Serializable interfac
(c). We can customize default serialization process by defining following methods in our class >readObject() and writeObject()
Note: We are not overriding these methods, we are defining them in our class.
(d). It provides less control over Serialization as it's not mandatory to define readObject() and writeObject() methods.
(e). Constructor is not called during deSerialization.
(a). It's not a marker interface.
It has method's called writeExternal() and readExternal()
(b). NO, we need to override writeExternal() and readExternal() for serialization process to happen.
(c). Serialization process is completely customized
We need to override Externalizable interface's writeExternal() and readExternal() methods.
(d). Externalizable provides you great control over serialization process as it is important to override writeExternal() and readExternal() methods.
(e). Constructor is called during deSerialization.
9. How can you avoid certain member variables of class from getting Serialized?
Mark member variables as static or transient, and those member variables will no more be a part of Serialization.
10. What are compatible and incompatible changes in Serialization process?
Compatible Changes:- Compatible changes are those changes which does not affect deSerialization process even if class was updated after being serialized (provided serialVersionUID has been declared)
(a). Adding new fields:- We can add new member variables in class.
(b). Adding writeObject()/readObject() methods:- We may add these methods to customize serialization process.
(c). Removing writeObject()/readObject() methods:- We may remove these methods and then default customization process will be used.
(d). Changing access modifier of a field:- The change to access modifiers i.e. public, default, protected, and private have no effect on the ability of serialization to assign values to the fields.
(e). Changing a field from static to non static OR changing transient filed to non transient field:- it's like addition of fields.
InCompatible Changes:- InCompatible changes are those changes which affect deSerialization process if class was updated after being serialized (provided serialVersionUID has been declared)
(a). Deletion of fields.
(b). Changing a non-static field to static or non transient field to transient field:- it's equal to deletion of fields.
(c). Modifying the writeObject() / readObject() method:- we must not modify these method, though adding or removing them completely is compatible change.
11. Why does serialization NOT save the value of static class attributes? Why static variables are not serialized?
The Java variables declared as static are not considered part of the state of an object since they are shared by all instances of that class. Saving static variables with each serialized object would have following problems:-
(a). It will make redundant copy of same variable in multiple objects which makes it in-efficient.
(b). The static variable can be modified by any object and a serialized copy would be stale or not in sync with current value.
12. How to Serialize a collection in java? How to serialize a ArrayList, Hashmap or Hashset object in Java?
All standard implementations of collections List, Set and Map interface already implement java.io.Serializable. All the commonly used collection classes like java.util.ArrayList, java.util.Vector, java.util.Hashmap, java.util.Hashtable, java.util.HashSet, java.util.TreeSet do implement Serializable. This means you do not really need to write anything specific to serialize collection objects.-
However you should keep following things in mind before you serialize a collection object - Make sure all the objects added in collection are Serializable. - Serializing the collection can be costly therefore make sure you serialize only required data isntead of serializing the whole collection. - In case you are using a custom implementation of Collection interface then you may need to implement serialization for it.
13. What Is the purpose of Java Serialization?
You can use Java serialization to perform the following tasks:-
(a). 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 .
(b). 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.
(c). 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.
(d). 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.
(e). Cross JVM Communication:- Serialization works the same across different JVMs irrespective of the architectures they are running on.
14. 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.
15. How many methods in the Serializable interface? Which methods of Serializable interface should I implement?
There is no method in the Serializable interface. Itís an empty interface which does not contain any methods. The Serializable interface acts as a marker, telling the object serialization tools that the class is serializable. So we do not implement any methods.
16. What happens to the object references included in the object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original object.
17. What happens to the static fields of a class during serialization?
There are three exceptions in which serialization doesnít necessarily read and write to the stream. These are as follows:-
(a). Serialization ignores static fields, because they are not part of any particular state.
(b). Base class fields are only handled if the base class itself is serializable.
(c). Transient fields.
18. What are Transient and Volatile Modifiers?
A transient variable is a variable that may not be serialized i.e. the value of the variable canít be written to the stream in a Serializable class. If you donít want some field to be serialized, you can mark that field transient or static. In such a case when the class is retrieved from the ObjectStream the value of the variable is null.
Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.
19. What interface must an object implement before it can be written to a stream as an object?
An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
20. What will happen if one of the members in the class doesn't implement Serializable interface?
One of the easy question about Serialization process in Java. 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 and this is why I always put a SerializableAlert (comment section in my code) , one of the code comment best practices, to instruct developer to remember this fact while adding a new field in a Serializable class.
21. Is it possible to serialize a singleton object?
Imagine you have a long-running app and want to be able to shut it down and later continue at the point where it was shut down (e.g. in order to do hardware maintenance). If the app uses a singleton that is stateful, you'd have to be able to save and restore the sigleton's state, which is most easily done by serializing it.
22. Are the static variables saved as the part of serialization?
No. The static variables belong to the class and not to an object they are not the part of the state of the object so they are not saved as the part of serialized object.
23. What are the alternatives to Serialization? If Serialization is not used, is it possible to persist or transfer an object using any other approach?
In case, Serialization is not used, Java objects can be serialized by many ways, some of the popular methods are listed below:
Saving object state to database, this is most common technique used by most applications. You can use ORM tools (e.g. hibernate) to save the objects in a database and read them from the database.
Xml based data transfer is another popular mechanism, and a lot of XML based web services use this mechanism to transfer data over network. Also a lot of tools save XML files to persist data/configurations.
24. Can you Customize Serialization process or can you override default Serialization process in Java?
The answer is yes you can. We all know that for serializing an object ObjectOutputStream.writeObject (saveThisobject) is invoked and for reading object ObjectInputStream.readObject() is invoked but there is one more thing which Java Virtual Machine provides you is to define these two method in your class.
If you define these two methods in your class then JVM will invoke these two methods instead of applying default serialization mechanism. You can customize behavior of object serialization and deserialization here by doing any kind of pre or post processing task
Important point to note is making these methods private to avoid being inherited, overridden or overloaded. Since only Java Virtual Machine can call private method integrity of your class will remain and Java Serialization will work as normal.
25. Which kind of variables is not serialized during Java Serialization?
This question asked sometime differently but the purpose is same whether Java developer knows specifics about static and transient variable or not. Since static variables belong to the class and not to an object they are not the part of the state of object so they are not saved during Java Serialization process. As Java Serialization only persist state of object and not object itself. Transient variables are also not included in java serialization process and are not the part of the objectís serialized state.
26. How can we tag properties to not to SERIALIZE?
Mark those properties with keyword transient.
27. How can you customize/override the default Serialization process in Java ?
As you know the Serialization process that is writing of object to the stream is handled by JVM, but if would like to do certain customization before serialization or after deserialization is done you can use writeObject and readObject method in your class which you are Serializing and JVM will automatically call them.
28. What happens in case of Inheritance where Parent Class is SERIALIZABLE?
If a class is serializable then all subclasses can also be SERIALIZED.
Either of classes needs not to have default constructor.