Top 44 Java Serialization Interview Questions
Q1. Can A Serialized Object Be Trmitted Through Network?
Yes, a Serialized object may be trmitted via the network as Java serialized object stays in shape of bytes. Serialized items also can be saved in Disk or database as Blob.
Q2. How To Prevent A Child Class From Being Serialized When It's Parent Class Already Implements Serializable Interface?
When the figure implements serializable then the child Class also be serializable although it would not put in force Serializable interface.
As a workaround, put into effect writeObject() and readObject() approach in the infant class and throw NotSerializableException from those methods.
Q3. Give Few Examples Of Incompatible Changes In Java Serialization?
Changing implementation from Serializable to Externalizable interface,
Deleting an existing Serializable field,
Changing non-trient subject to trient, non-static to static,
Changing the sphere kind,
Updating the class package deal.
Modifying the writeObject() / readObject() method, we must not modify these techniques, although including or removing is a well suited alternate.
Q4. How To Create A Serializable Class In Java?
Implement java.Io.Serializable interface in the Java elegance and JVM will permit to serialize its items in default serialization layout.
Q5. Which Method Is Used During Serialization And Deserialization Process In Java?
Java Serialization is carried out through java.Io.ObjectOutputStream class, a filter flow that's wrapped round a lower-stage byte stream to deal with the serialization mechanism. To shop any item through serialization mechanism we call ObjectOutputStream.WriteObject(saveThisobject) and to deserialize that object we call ObjectInputStream.ReadObject() approach.
Q6. What Would Happen If The Serialversionuid Of An Object Is Not Defined?
If you do not define serialVersionUID to your serilizable magnificence, Java compiler will make one via developing a hash code the usage of most of your class attributes and features. When an item receives serialized, this hash code is stamped at the object which is called the SerialVersionUID of that object. This ID is required for the model manipulate of an object. SerialVersionUID can be specified within the class file additionally. In case, this ID isn't specified by means of you, then Java compiler will regenerate a SerialVersionUID based on updated elegance and it'll not be feasible for the already serialized class to recover while a category area is added or changed. Its encouraged that you constantly claim a serialVersionUID in your Serializable training.
Q7. What Are The Alternatives To Serialization? If Serialization Is Not Used, Is It Possible To Persist Or Trfer An Object Using Any Other Approach?
In case, Serialization isn't used, Java gadgets can be serialized by means of many methods, a number of the popular methods are indexed beneath:
Saving item country to database, this is most commonplace approach used by maximum packages. You can use ORM tools (e.G. Hibernate) to save the gadgets in a database and examine them from the database.
Xml based totally records trfer is some other famous mechanism, and numerous XML based internet services use this mechanism to trfer information over network. Also lots of tools keep XML documents to persist facts/configurations.
JSON Data Trfer - is currently famous statistics trfer format. A lot of internet services are being advanced in JSON because of its small footprint and inherent integration with internet browser due to JavaScript format.
Q8. Does Setting The Serialversionuid Class Field Improve Java Serialization Performance?
Declaring an explicit serialVersionUID area to your instructions saves some CPU time only the primary time the JVM method serializes a given Class. However the gain is not widespread, In case if you have not declared the serialVersionUID its cost is computed by way of JVM as soon as and finally kept in a soft cache for future use.
Q9. Why Does Serialization Not Save The Value Of Static Class Attributes? Why Static Variables Are Not Serialized?
The Java variables declared as static aren't considered a part of the kingdom of an item on account that they're shared with the aid of all times of that elegance. Saving static variables with each serialized item might have following troubles.
It will make redundant reproduction of same variable in a couple of objects which makes it in-green.
The static variable can be modified with the aid of any item and a serialized reproduction might be stale or not in sync with modern price.
Q10. How Do I Serialize A Collection In Java?
All trendy implementations of collections List, Set and Map interface already put into effect java.Io.Serializable. However ensure all of the objects brought in collection are Serializable as well.
Q11. What Is A Serial Version Uid (serialversionuid) And Why Should I Use It? How To Generate One?
The serialVersionUID represents your class version, and also you have to alternate it if the contemporary model of your magnificence is not backwards well suited with its earlier versions. This is extract from Java API Documentation
The serialization runtime pals with each serializable magnificence a version wide variety, referred to as a serialVersionUID, that's used all through deserialization to verify that the sender and receiver of a serialized item have loaded lessons for that object which are well suited with respect to serialization.
Most of the instances, we in all likelihood do now not use serialization without delay. In such instances, I would suggest to generate a default serializable uid by using clicking the fast restoration alternative in eclipse.
Q12. What Are Trient Variables? What Role Do They Play In Serialization Process?
The trient keyword in Java is used to signify that a subject ought to not be serialized. Once the technique of de-serialization is carried out, the trient variables do no longer go through a trade and hold their default price. Marking unwanted fields as trient allow you to improve the serialization overall performance. Below is a simple instance where you could see the use of trient keyword.
Class MyVideo implements Serializable
non-public Video video;
non-public trient Image thumbnailVideo;
non-public void generateThumbnail()
// Generate thumbnail.
Private void readObject(ObjectInputStream inputStream)
throws IOException, ClassNotFoundException
inputStream.DefaultReadObject();
generateThumbnail();
Q13. How To Improve Java Serialization Performance?
Java serialization overall performance at once rely upon the quantity and size of attributes within the Java item. To enhance the overall performance,
Mark the undesirable or non Serializable attributes as trient.
Save most effective the state of the item, not the derived attributes.Some instances, serializing them may be costly.
Serialize attributes only with NON-default values.
Use Externalizable interface and implement the readExternal and writeExternal techniques to dynamically perceive the attributes to be serialized.
Q14. How To Generate A Serialversionuid In Java?
There are 3 ways to create a serialVersionUID price.
Using serialVer command bundled with JDK, pass the serializable elegance name as command parameter to get its model identifier.
Using Eclipse IDE, hover at the magnificence and from the context menu select Add default serial model ID, or Add generated serial model ID.
Assign your personal price and postfix with 'L'.
Non-public static very last long serialVersionUID = 19L;
Q15. List Few Alternatives To Java Serialization?
Saving object kingdom to database the usage of ORM equipment,
Xml primarily based facts trfer,
and JSON Data Trfer.
Q16. What Are The Ways To Speed Up Object Serialization? How To Improve Serialization Performance?
The default Java Serialization mechanism is simply beneficial, but it can have a honestly bad performance primarily based for your application and business necessities. The serialization process performance heavily depends on the range and length of attributes you will serialize for an object. Below are some hints you can use for rushing up the marshaling and un-marshaling of gadgets in the course of Java serialization manner.
Mark the undesirable or non Serializable attributes as trient. This is a uncomplicated gain due to the fact your attributes for serialization are genuinely marked and can be easily executed the usage of Serialzable interface itself.
Save handiest the state of the item, not the derived attributes. Some times we maintain the derived attributes as a part of the item however serializing them can be pricey. Therefore recall calcualting them in the course of de-serialization system.
Serialize attributes simplest with NON-default values. For examples, serializing a int variable with value 0 is just going to take more area but, deciding on not to serialize it might prevent plenty of performance. This technique can avoid some forms of attributes taking unwanted space. This will require use of Externalizable interface for the reason that characteristic serialization is decided at runtime based totally on the price of each attribute.
Use Externalizable interface and put in force the readExternal and writeExternal methods to dynamically discover the attributes to be serialized. Some instances there may be a custom common sense used for serialization of diverse attributes.
Q17. What Happens When One Of The Members Of The Class Does Not Implement Serializable Interface?
At runtime NotSerializableException is thrown while attempt to serialize the elegance while one of the contributors does now not put into effect serializable interface.
Q18. Give More Examples Of Compatible Changes In Java Serialization?
Adding a new subject will not affect serialization. The newly introduced discipline might be set to its default values whilst the item of an older version of the class is unmarshaled.
Changes In get entry to modifiers along with non-public, public, protected or default is well matched seeing that they are not meditated inside the serialized object stream.
Changing a trient discipline to a non-trient field, static to non-static are well suited adjustments.
Adding or doing away with writeObject()/readObject() techniques.
Q19. Is Externalizable A Marker Interface In Java?
No. It has two strategies readExternal and writeExternal to be applied.
Q20. How Do I Prevent Deserialization Process Creating Another Instance Of Singleton Class?
Use readResolve method to go back the identical instance of a class, instead of developing a new instance.
Q21. What Happens When A Class Does Not Define Serialversionuid In Java?
If the serialVersionUID isn't always described, then after any amendment made in elegance, we gained?T be able to deSerialize present objects for equal elegance due to the fact serialVersionUID generated via Java compiler for the changed magnificence might be one of a kind from the vintage serialized object. Deserialization manner will fail by means of throwing java.Io.Invalid Class Exception.
Q22. Which Variables Are Not Serialized During Java Serialization?
Static and trient variables can not be serialized.
Q23. Does Having Serialversionuid Variable Improve Java Serialization Performance?
Declaring a serialVersionUID discipline in a Java magnificence saves CPU time the primary time the JVM process serializes a given Class. However the performance gain isn't always very big, In case if you have now not declared the serialVersionUID its price is computed by JVM once and subsequently kept in a gentle cache for destiny use.
Q24. Why Do We Need Externalizable Interface?
Externalizable Interface permits us to manipulate serialization mechanism which might also assist enhance application performance.
Q25. What Are The Compatible And Incompatible Changes In Java Serialization Mechanism?
Adding new subject or method is a well matched exchange and converting magnificence hierarchy or UN-imposing Serializable interface are non well suited changes.
Q26. Is It Possible To Customize The Serialization Process? How Can We Customize The Serialization Process?
Yes, the serialization procedure may be customized. When an item is serialized, objectOutputStream.WriteObject (to store this object) is invoked and when an item is study, ObjectInputStream.ReadObject () is invoked. What the majority do not recognize is that Java Virtual Machine provides you with an choice to define these strategies as per your needs. Once this is carried out, those strategies could be invoked by way of the JVM as opposed to the application of the default serialization manner. Classes that require unique coping with in the course of the serialization and deserialization system must put in force unique methods with these precise signatures:
non-public void writeObject(java.Io.ObjectOutputStream out)
throws IOException
personal void readObject(java.Io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
private void readObjectNoData()
throws ObjectStreamException;
Q27. Is The Constructor Invoked When A Java Object Is De-serialized?
If the magnificence implements Serializable, the constructor isn't known as during deserialization system. However, if the class implements Externalizable, the constructor is called in the course of deserialization manner.
Q28. Difference Between Readresolve And Readobject Methods In Java Serialization?
For Serializable and Externalizable lessons, the readResolve technique allows a class to update/clear up the object examine from the stream before it is returned to the caller. By implementing the readResolve approach, a category can immediately manipulate the types and instances of its very own instances being deserialized. This method is known as whilst ObjectInputStream has read an object from the flow and is preparing to go back it to the caller.
For serializable objects, the readObject method permits a category to govern the deserialization of its own fields and held answerable for restoring the kingdom of the elegance.
Q29. How To Serialize A Collection In Java? How To Serialize A Arraylist, Hashmap Or Hashset Object In Java?
All preferred implementations of collections List, Set and Map interface already put into effect java.Io.Serializable. All the usually used collection training like java.Util.ArrayList, java.Util.Vector, java.Util.Hashmap, java.Util.Hashtable, java.Util.HashSet, java.Util.TreeSet do put in force Serializable. This me you do now not really need to put in writing anything unique to serialize collection items. However you must preserve following matters in mind earlier than you serialize a group object - Make positive all the items brought in collection are Serializable. - Serializing the collection may be luxurious consequently make sure you serialize most effective required information isntead of serializing the entire collection. - In case you're the use of a custom implementation of Collection interface then you may want to put into effect serialization for it.
Q30. What Is Trient Variable In Java?
Trient variables aren't blanketed within the serialization and are not the a part of the object's serialized state. A trient variable may be created through specifying trient key-word.
Q31. Is Serializable A Marker Interface In Java?
Yes. It has no strategies.
Q32. What Is Serialversionuid In Java?
Every time an object is serialized the Java serialization mechanism mechanically computes a hash price known as serialVersionUID. ObjectStreamClass's computeSerialVersionUID() approach passes the class call, looked after member names, modifiers, and interfaces to the comfy hash algorithm (SHA), which returns a hash value.The serialVersionUID is likewise referred to as suid.
Q33. Is Constructor Of Parent Class Called During Deserialization Process Of Child Class?
If superclass implements Serializable - constructor isn't always referred to as at the same time as if the superclass doesn't put into effect Serializable - constructor is known as at some stage in DeSerialization system of infant magnificence.
Q34. How Can A Sub-magnificence Of Serializable Super Class Avoid Serialization? If Serializable Interface Is Implemented By The Super Class Of A Class, How Can The Serialization Of The Class Be Avoided?
In Java, if the first-rate magnificence of a class is enforcing Serializable interface, it me that it's far already serializable. Since, an interface cannot be unimplemented, it isn't viable to make a category non-serializable. However, the serialization of a brand new elegance can be averted. For this, writeObject () and readObject() methods must be applied for your elegance so that a Not Serializable Exception may be thrown via those techniques. And, this may be achieved by way of customizing the Java Serialization technique. 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 magnificence”);
private void readObject(java.Io.ObjectInputStream in)
throws IOException, ClassNotFoundException
throw new NotSerializableException(“Can now not serialize this magnificence”);
non-public void readObjectNoData()
throws ObjectStreamException;
throw new NotSerializableException(“Can not serialize this elegance”);
Q35. Is There Any Limit On The Size Of A Serialized Object?
Yes, it's far limited by means of the quantity of memory your JVM can allocate to the creation and maintenance of your item. As for writing it out to disk, it's miles restricted by means of the maximum document length of the underlying OS. Linux, as an example, has a 2GB restriction on one record.
Q36. Do Primitive Data Types Involve In Serialization?
Yes, all of the primitive records kinds are part of serialization.
Q37. Do We Need To Implement Any Method When Using Serializable Interface?
No. Serializable interface is a marker interface.
Q38. Why Static Variables Are Not Serialized In Java?
The static variables are magnificence stage variables and aren't the a part of the item country so they're now not stored because the part of serialized object.
Q39. What Changes Are Compatible And Incompatible To The Mechanism Of Java Serialization?
This is one of a tough and intricate questions and wering this efficiently could mean you're an expert in Java Serialization concept. In an already serialized item, the maximum tough venture is to alternate the structure of a category while a new subject is introduced or removed. As in line with the specifications of Java Serialization, addition of any method or field is considered to be a like minded alternate while converting of class hierarchy or non-implementation of Serializable interface is considered to be a non-compatible change. You can undergo the Java serialization specification for the significant list of compatible and non-well suited adjustments. If a serialized item need to be compatible with an older version, it's miles important that the more recent model follows some regulations for well matched and incompatible adjustments. A well suited change to the imposing magnificence is one that may be applied to a new edition of the magnificence, which nevertheless continues the object circulate like minded with older model of identical elegance.
Some Simple Examples of compatible changes are:
Addition of a new discipline or class will now not have an effect on serialization, on account that any new facts in the circulate is without a doubt neglected by older versions. The newly added field can be set to its default values while the object of an older version of the magnificence is un marshaled.
The get admission to modifiers alternate (like non-public, public, covered or default) is like minded because they're not meditated inside the serialized object stream.
Changing a trient discipline to a non-trient field is compatible change when you consider that it's far much like adding a discipline.
Changing a static area to a non-static discipline is well matched trade due to the fact it is also much like adding a field.
Some Simple Examples of incompatible changes are:
Changing implementation from Serializable to Externalizable interface can't be achieved since this can result in the introduction of an incompatible item move.
Deleting a present Serializable fields will purpose a hassle.
Changing a non-trient area to a trient subject is incompatible exchange for the reason that it is much like deleting a discipline.
Changing a non-static subject to a static discipline is incompatible exchange for the reason that it's also similar to deleting a discipline.
Changing the kind of a attribute within a category might be incompatible, on account that this would cause a failure when trying to examine and convert the authentic discipline into the new discipline.
Changing the package of sophistication is incompatible. Since the absolutely-certified magnificence call is written as part of the
Java serialization is one of the most normally misunderstood regions. Many developers still suppose its handiest used for saving gadgets on the record system.
Hope you found this list beneficial. Can you suspect of a questions that is not a part of this list? Please don't forget to percentage it with me in feedback phase & I will try and consist of it within the listing.
Q40. What Is The Value Of A Trient Variable After Deserialization?
It will be set to its default cost. For example, an int trient variable will be set to zero.
Q41. List Few Differences Between Serializable And Externalizable In Java?
Serializable:
Serializable has its very own default serialization manner, we simply need to implement Serializable interface. We can customise default serialization method by defining following methods in our elegance, readObject() and writeObject().Note: We are not overriding those methods, we're defining them in our elegance.
This is a marker interface, does no longer have any strategies.
Constructor is not known as throughout deSerialization.
Externalizable:
Override writeExternal() and readExternal() for serialization technique to show up when implementing Externalizable interface.
This has 2 strategies readExternal and writeExternal, hence it isn't a marker interface.
Constructor is called throughout deSerialization.
Q42. When To Use Serializable Vs Externalizable?
Use of trient keyword permits selective characteristic serialization, but, use of Externalizable interface may be genuinely powerful in some cases when you have to serialize only some dynamically decided on attributes of a huge object.
Q43. Difference Between Serializable And Externalizable Interface In Java?
Externalizable gives writeExternal() and readExternal() techniques which gives flexibility to override java serialization mechanism in place of the use of on default serialization.
Q44. What Is Serialization In Java?
Java serialization is the technique via which Java objects are serialized by means of storing item's state into a report with extension .Ser. Restoring object's kingdom from that document is called deserialization.
Object Serialization converts Java object into a binary format which can be persevered to disk or sent over community to different JVM.

