Serialization in java is a mechanism of writing the state of an object into a byte stream. It is mainly used in EJB, JPA, Hibernate, RMI, and JMS technologies Object serialization is the process of saving an object's state to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time. Getting certified in Java programming language will create more opportunities in the competitive world. Strong Communication Skills - Should be interacting with client stakeholders to probe a technical problem. Wisdomjobs has interview questions which are exclusively designed for job seekers to assist them in clearing job interviews. Java Serialization interview questions are useful to attend job interviews and get shortlisted for job position.
Question 1. What Is Serialization In Java?
Answer :
Java serialization is the process by which Java objects are serialized by storing object's state into a file with extension .ser. Restoring object's state from that file is called deserialization.
Object Serialization converts Java object into a binary format which can be persisted to disk or sent over network to other JVM.
Question 2. How To Create A Serializable Class In Java?
Answer :
Implement java.io.Serializable interface in the Java class and JVM will allow to serialize its objects in default serialization format.
Question 3. Difference Between Serializable And Externalizable Interface In Java?
Answer :
Externalizable provides writeExternal() and readExternal() methods which gives flexibility to override java serialization mechanism instead of using on default serialization.
Question 4. Why Do We Need Externalizable Interface?
Answer :
Externalizable Interface allows us to control serialization mechanism which may help improve application performance.
Question 5. Is Serializable A Marker Interface In Java?
Answer :
Yes. It has no methods.
Question 6. Can A Serialized Object Be Transmitted Through Network?
Answer :
Yes, a Serialized object can be transmitted via the network as Java serialized object remains in form of bytes. Serialized objects can also be stored in Disk or database as Blob.
Question 7. Which Variables Are Not Serialized During Java Serialization?
Answer :
Static and transient variables cannot be serialized.
Question 8. What Is Serialversionuid In Java?
Answer :
Every time an object is serialized the Java serialization mechanism automatically computes a hash value called serialVersionUID. ObjectStreamClass's computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
Question 9. Do We Need To Implement Any Method When Using Serializable Interface?
Answer :
No. Serializable interface is a marker interface.
Question 10. What Is Transient Variable In Java?
Answer :
Transient variables are not included in the serialization and are not the part of the object's serialized state. A transient variable can be created by specifying transient keyword.
Question 11. Why Static Variables Are Not Serialized In Java?
Answer :
The static variables are class level variables and are not the part of the object state so they are not saved as the part of serialized object.
Question 12. Is Externalizable A Marker Interface In Java?
Answer :
No. It has two methods readExternal and writeExternal to be implemented.
Answer :
At runtime NotSerializableException is thrown when try to serialize the class when one of the members does not implement serializable interface.
Answer :
When the parent implements serializable then the child Class also be serializable although it doesn't implement Serializable interface.
As a workaround, implement writeObject() and readObject() method in the child class and throw NotSerializableException from those methods.
Question 15. What Are The Compatible And Incompatible Changes In Java Serialization Mechanism?
Answer :
Adding new field or method is a compatible change and changing class hierarchy or UN-implementing Serializable interface are non compatible changes.
Question 16. How To Improve Java Serialization Performance?
Answer :
Java serialization performance directly rely on the number and size of attributes in the Java object. To improve the performance,
Question 17. When To Use Serializable Vs Externalizable?
Answer :
Use of transient keyword enables selective attribute serialization, however, use of Externalizable interface can be really effective in some cases when you have to serialize only some dynamically selected attributes of a large object.
Question 18. List Few Alternatives To Java Serialization?
Answer :
Saving object state to database using ORM tools,
Xml based data transfer,
and JSON Data Transfer.
Question 19. How Do I Serialize A Collection In Java?
Answer :
All standard implementations of collections List, Set and Map interface already implement java.io.Serializable. However ensure all the objects added in collection are Serializable as well.
Question 20. Give More Examples Of Compatible Changes In Java Serialization?
Answer :
Question 21. Give Few Examples Of Incompatible Changes In Java Serialization?
Answer :
Question 22. Which Method Is Used During Serialization And Deserialization Process In Java?
Answer :
Java Serialization is done by java.io.ObjectOutputStream class, a filter stream which is wrapped around a lower-level byte stream to handle the serialization mechanism. To store any object via serialization mechanism we call ObjectOutputStream.writeObject(saveThisobject) and to deserialize that object we call ObjectInputStream.readObject() method.
Question 23. What Is The Value Of A Transient Variable After Deserialization?
Answer :
It will be set to its default value. For example, an int transient variable will be set to zero.
Question 24. Does Having Serialversionuid Variable Improve Java Serialization Performance?
Answer :
Declaring a serialVersionUID field in a Java class saves CPU time the first time the JVM process serializes a given Class. However the performance gain is not very significant, In case when you have not declared the serialVersionUID its value is computed by JVM once and subsequently kept in a soft cache for future use.
Question 25. Is The Constructor Invoked When A Java Object Is De-serialized?
Answer :
If the class implements Serializable, the constructor is not called during deserialization process. However, if the class implements Externalizable, the constructor is called during deserialization process.
Question 26. How To Generate A Serialversionuid In Java?
Answer :
There are 3 ways to create a serialVersionUID value.
Using serialVer command bundled with JDK, pass the serializable class name as command parameter to get its version identifier.
Using Eclipse IDE, hover at the class and from the context menu choose Add default serial version ID, or Add generated serial version ID.
Assign your own value and postfix with 'L'.
private static final long serialVersionUID = 19L;
Question 27. List Few Differences Between Serializable And Externalizable In Java?
Answer :
Serializable:
Externalizable:
Question 28. Do Primitive Data Types Involve In Serialization?
Answer :
Yes, all the primitive data types are part of serialization.
Question 29. What Happens When A Class Does Not Define Serialversionuid In Java?
Answer :
If the serialVersionUID is not defined, then after any modification made in class, we won?t be able to deSerialize existing objects for same class because serialVersionUID generated by Java compiler for the modified class will be different from the old serialized object. Deserialization process will fail by throwing java.io.Invalid Class Exception.
Question 30. Is Constructor Of Parent Class Called During Deserialization Process Of Child Class?
Answer :
If superclass implements Serializable - constructor is not called while if the superclass doesn't implement Serializable - constructor is called during DeSerialization process of child class.
Question 31. Difference Between Readresolve And Readobject Methods In Java Serialization?
Answer :
For Serializable and Externalizable classes, the readResolve method allows a class to replace/resolve the object read from the stream before it is returned to the caller. By implementing the readResolve method, a class can directly control the types and instances of its own instances being deserialized. This method is called when ObjectInputStream has read an object from the stream and is preparing to return it to the caller.
For serializable objects, the readObject method allows a class to control the deserialization of its own fields and held responsible for restoring the state of the class.
Question 32. How Do I Prevent Deserialization Process Creating Another Instance Of Singleton Class?
Answer :
Use readResolve method to return the same instance of a class, rather than creating a new instance.
Question 33. Is There Any Limit On The Size Of A Serialized Object?
Answer :
Yes, it is limited by the amount of memory your JVM can allocate to the creation and maintenance of your object. As for writing it out to disk, it is limited by the maximum file size of the underlying OS. Linux, as an example, has a 2GB limit on one file.
Answer :
Answer :
The serialVersionUID represents your class version, and you should change it if the current version of your class is not backwards compatible with its earlier versions. This is extract from Java API Documentation
The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which 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.
Most of the times, we probably do not use serialization directly. In such cases, I would suggest to generate a default serializable uid by clicking the quick fix option in eclipse.
Question 36. What Would Happen If The Serialversionuid Of An Object Is Not Defined?
Answer :
If you don't define serialVersionUID in your serilizable class, Java compiler will make one by creating a hash code using most of your class attributes and features. When an object gets serialized, this hash code is stamped on the object which is known as the SerialVersionUID of that object. This ID is required for the version control of an object. SerialVersionUID can be specified in the class file also. In case, this ID is not specified by you, then Java compiler will regenerate a SerialVersionUID based on updated class and it will not be possible for the already serialized class to recover when a class field is added or modified. Its recommended that you always declare a serialVersionUID in your Serializable classes.
Question 37. Does Setting The Serialversionuid Class Field Improve Java Serialization Performance?
Answer :
Declaring an explicit serialVersionUID field in your classes saves some CPU time only the first time the JVM process serializes a given Class. However the gain is not significant, In case when you have not declared the serialVersionUID its value is computed by JVM once and subsequently kept in a soft cache for future use.
Answer :
In case, Serialization is not used, Java objects can be serialized by many ways, some of the popular methods are listed below:
Question 39. What Are Transient Variables? What Role Do They Play In Serialization Process?
Answer :
The transient keyword in Java is used to indicate that a field should not be serialized. Once the process of de-serialization is carried out, the transient variables do not undergo a change and retain their default value. Marking unwanted fields as transient can help you boost the serialization performance. Below is a simple example where you can see the use of transient keyword.
class MyVideo implements Serializable
{
private Video video;
private transient Image thumbnailVideo;
private void generateThumbnail()
{
// Generate thumbnail.
}
private void readObject(ObjectInputStream inputStream)
throws IOException, ClassNotFoundException
{
inputStream.defaultReadObject();
generateThumbnail();
}
}
Answer :
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.
Answer :
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.
Answer :
Yes, the serialization process can be customized. When an object is serialized, objectOutputStream.writeObject (to save this object) is invoked and when an object is read, ObjectInputStream.readObject () is invoked. What most people do not know is that Java Virtual Machine provides you with an option to define these methods as per your needs. Once this is done, these two methods will be invoked by the JVM instead of the application of the default serialization process. Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
private void readObjectNoData()
throws ObjectStreamException;
Answer :
In Java, if the super class of a class is implementing Serializable interface, it means that it is already serializable. Since, an interface cannot be unimplemented, it is not possible to make a class non-serializable. However, the serialization of a new class can be avoided. For this, writeObject () and readObject() methods should be implemented in your class so that a Not Serializable Exception can be thrown by these methods. And, this can be done by customizing the Java Serialization process. Below the code that demonstrates it
class MySubClass extends SomeSerializableSuperClass {
private void writeObject(java.io.ObjectOutputStream out)
throws IOException {
throw new NotSerializableException(“Can not serialize this class”);
}
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException {
throw new NotSerializableException(“Can not serialize this class”);
}
private void readObjectNoData()
throws ObjectStreamException; {
throw new NotSerializableException(“Can not serialize this class”);
}
}
Question 44. What Changes Are Compatible And Incompatible To The Mechanism Of Java Serialization?
Answer :
This is one of a difficult and tricky questions and answering this correctly would mean you are an expert in Java Serialization concept. In an already serialized object, the most challenging task is to change the structure of a class when a new field is added or removed. As per the specifications of Java Serialization, addition of any method or field is considered to be a compatible change whereas changing of class hierarchy or non-implementation of Serializable interface is considered to be a non-compatible change. You can go through the Java serialization specification for the extensive list of compatible and non-compatible changes. If a serialized object need to be compatible with an older version, it is necessary that the newer version follows some rules for compatible and incompatible changes. A compatible change to the implementing class is one that can be applied to a new version of the class, which still keeps the object stream compatible with older version of same class.
Some Simple Examples of compatible changes are:
Some Simple Examples of incompatible changes are:
Java serialization is one of the most commonly misunderstood areas. Many developers still think its only used for saving objects on the file system.
Hope you found this list useful. Can you think of a questions that is not part of this list? Please don't forget to share it with me in comments section & I will try to include it in the list.
Java Serialization Related Tutorials |
|
---|---|
Java Script Tutorial | Adv Java Tutorial |
J2EE Tutorial | Core Java Tutorial |
JSP Tutorial | Java-Springs Tutorial |
Java Tutorial | Java 8 Tutorial |
Java Serialization Practice Test
All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.