YouTube Icon

Interview Questions.

Top 100+ Java Serialization Interview Questions And Answers - May 31, 2020

fluid

Top 100+ Java Serialization Interview Questions And Answers

Question 1. What Is Serialization In Java?

Answer :

Java serialization is the manner by which Java objects are serialized via storing object's state into a document with extension .Ser. Restoring item's state from that document is referred to as deserialization.

Object Serialization converts Java object right into a binary format which may be continued to disk or despatched over network to other JVM.

Question 2. How To Create A Serializable Class In Java?

Answer :

Implement java.Io.Serializable interface within the Java magnificence and JVM will allow to serialize its objects in default serialization format.

Java Script Interview Questions
Question three. Difference Between Serializable And Externalizable Interface In Java?

Answer :

Externalizable gives writeExternal() and readExternal() techniques which gives flexibility to override java serialization mechanism instead of using on default serialization.

Question four. Why Do We Need Externalizable Interface?

Answer :

Externalizable Interface allows us to govern serialization mechanism which may also help improve application performance.

Java Script Tutorial
Question 5. Is Serializable A Marker Interface In Java?

Answer :

Yes. It has no strategies.

Adv Java Interview Questions
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 items also can be saved in Disk or database as Blob.

Question 7. Which Variables Are Not Serialized During Java Serialization?

Answer :

Static and transient variables cannot be serialized.

Adv Java Tutorial J2EE Interview Questions
Question 8. What Is Serialversionuid In Java?

Answer :

Every time an item is serialized the Java serialization mechanism mechanically computes a hash price referred to as serialVersionUID. ObjectStreamClass's computeSerialVersionUID() technique passes the class call, looked after member names, modifiers, and interfaces to the comfy hash set of rules (SHA), which returns a hash cost.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.

Core Java Interview Questions
Question 10. What Is Transient Variable In Java?

Answer :

Transient variables aren't blanketed inside the serialization and are not the part of the object's serialized nation. A transient variable can be created by means of specifying temporary keyword.

J2EE Tutorial
Question 11. Why Static Variables Are Not Serialized In Java?

Answer :

The static variables are magnificence level variables and are not the a part of the object state so they may be no longer saved because the part of serialized item.

JSP Interview Questions
Question 12. Is Externalizable A Marker Interface In Java?

Answer :

No. It has  methods readExternal and writeExternal to be implemented.

Java Script Interview Questions
Question 13. What Happens When One Of The Members Of The Class Does Not Implement Serializable Interface?

Answer :

At runtime NotSerializableException is thrown when try and serialize the elegance whilst one of the contributors does not put into effect serializable interface.

Core Java Tutorial
Question 14. How To Prevent A Child Class From Being Serialized When It's Parent Class Already Implements Serializable Interface?

Answer :

When the determine implements serializable then the kid Class also be serializable even though it doesn't implement Serializable interface.

As a workaround, enforce writeObject() and readObject() technique within the toddler 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 approach is a like minded alternate and changing elegance hierarchy or UN-imposing Serializable interface are non compatible modifications.

Java-Springs Interview Questions
Question 16. How To Improve Java Serialization Performance?

Answer :

Java serialization overall performance at once depend on the variety and size of attributes within the Java item. To enhance the overall performance,

Mark the undesirable or non Serializable attributes as transient.
Save best the state of the item, no longer the derived attributes.Some times, serializing them can be costly.
Serialize attributes simplest with NON-default values.
Use Externalizable interface and enforce the readExternal and writeExternal strategies to dynamically become aware of the attributes to be serialized.
JSP Tutorial
Question 17. When To Use Serializable Vs Externalizable?

Answer :

Use of brief keyword permits selective attribute serialization, however, use of Externalizable interface can be actually powerful in a few instances if you have to serialize only a few dynamically selected attributes of a large object.

JMS(Java Message Service) Interview Questions
Question 18. List Few Alternatives To Java Serialization?

Answer :

Saving object state to database the use of ORM equipment,

Xml based information switch,

and JSON Data Transfer.

Adv Java Interview Questions
Question 19. How Do I Serialize A Collection In Java?

Answer :

All preferred implementations of collections List, Set and Map interface already enforce java.Io.Serializable. However ensure all of the items brought in series are Serializable as well.

Java-Springs Tutorial
Question 20. Give More Examples Of Compatible Changes In Java Serialization?

Answer :

Adding a new area will no longer have an effect on serialization. The newly added field can be set to its default values when the item of an older model of the elegance is unmarshaled.
Changes In get entry to modifiers which include non-public, public, covered or default is well suited considering they're not reflected within the serialized object circulate.
Changing a transient area to a non-transient discipline, static to non-static are compatible modifications.
Adding or doing away with writeObject()/readObject() techniques.
Java applet Interview Questions
Question 21. Give Few Examples Of Incompatible Changes In Java Serialization?

Answer :

Changing implementation from Serializable to Externalizable interface,
Deleting an present Serializable discipline,
Changing non-brief area to temporary, non-static to static,
Changing the sector kind,
Updating the magnificence package deal.
Modifying the writeObject() / readObject() approach, we should not adjust these techniques, though including or casting off is a well matched exchange.
Question 22. Which Method Is Used During Serialization And Deserialization Process In Java?

Answer :

Java Serialization is done by means of java.Io.ObjectOutputStream elegance, a filter movement which is wrapped round a decrease-degree byte circulate to handle the serialization mechanism. To store any item through serialization mechanism we name ObjectOutputStream.WriteObject(saveThisobject) and to deserialize that object we name ObjectInputStream.ReadObject() technique.

Java Tutorial
Question 23. What Is The Value Of A Transient Variable After Deserialization?

Answer :

It will be set to its default price. For instance, an int temporary variable will be set to zero.

Java Interview Questions
Question 24. Does Having Serialversionuid Variable Improve Java Serialization Performance?

Answer :

Declaring a serialVersionUID subject in a Java class saves CPU time the first time the JVM system serializes a given Class. However the overall performance benefit isn't always very large, In case if you have no longer declared the serialVersionUID its value is computed by means of JVM as soon as and subsequently stored in a soft cache for destiny use.

J2EE Interview Questions
Question 25. Is The Constructor Invoked When A Java Object Is De-serialized?

Answer :

If the magnificence implements Serializable, the constructor isn't known as at some point of deserialization process. However, if the elegance implements Externalizable, the constructor is referred to as in the course of deserialization system.

Java 8 Tutorial
Question 26. How To Generate A Serialversionuid In Java?

Answer :

There are three ways to create a serialVersionUID price.

Using serialVer command bundled with JDK, pass the serializable class call as command parameter to get its version identifier.

Using Eclipse IDE, hover on the magnificence and from the context menu select Add default serial model ID, or Add generated serial version ID.

Assign your own value and postfix with 'L'.

Non-public static very last lengthy serialVersionUID = 19L;

Java 8 Interview Questions
Question 27. List Few Differences Between Serializable And Externalizable In Java?

Answer :

Serializable:

Serializable has its own default serialization technique, we simply want to put into effect Serializable interface. We can customise default serialization technique by means of defining following methods in our class, readObject() and writeObject().Note: We are not overriding those techniques, we are defining them in our magnificence.
This is a marker interface, does no longer have any methods.
Constructor isn't always known as at some point of deSerialization.
Externalizable:

Override writeExternal() and readExternal() for serialization procedure to appear whilst implementing Externalizable interface.
This has 2 techniques readExternal and writeExternal, for this reason it isn't always a marker interface.
Constructor is referred to as all through deSerialization.
Core Java Interview Questions
Question 28. Do Primitive Data Types Involve In Serialization?

Answer :

Yes, all of the primitive statistics sorts are a part of serialization.

Question 29. What Happens When A Class Does Not Define Serialversionuid In Java?

Answer :

If the serialVersionUID isn't always described, then after any modification made in magnificence, we received?T be able to deSerialize existing objects for same elegance due to the fact serialVersionUID generated by means of Java compiler for the changed magnificence can be one-of-a-kind from the old serialized object. Deserialization procedure will fail by throwing java.Io.Invalid Class Exception.

JQuery Mobile Interview Questions
Question 30. Is Constructor Of Parent Class Called During Deserialization Process Of Child Class?

Answer :

If superclass implements Serializable - constructor isn't referred to as while if the superclass doesn't put into effect Serializable - constructor is called all through DeSerialization manner of baby magnificence.

Question 31. Difference Between Readresolve And Readobject Methods In Java Serialization?

Answer :

For Serializable and Externalizable training, the readResolve approach allows a category to replace/resolve the item read from the movement before it's far back to the caller. By imposing the readResolve technique, a category can directly control the sorts and instances of its own times being deserialized. This approach is known as when ObjectInputStream has read an object from the flow and is getting ready to return it to the caller.

For serializable objects, the readObject approach allows a class to manipulate 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 technique to return the same instance of a category, as opposed to growing a brand new instance.

Advanced jQuery Interview Questions
Question 33. Is There Any Limit On The Size Of A Serialized Object?

Answer :

Yes, it is restricted with the aid of the quantity of memory your JVM can allocate to the introduction and maintenance of your item. As for writing it out to disk, it's far restricted with the aid of the maximum record length of the underlying OS. Linux, as an instance, has a 2GB limit on one report.

JSP Interview Questions
Question 34. What Are The Ways To Speed Up Object Serialization? How To Improve Serialization Performance?

Answer :

The default Java Serialization mechanism is really useful, but it may have a absolutely awful overall performance based to your application and enterprise necessities. The serialization system overall performance closely depends at the number and length of attributes you are going to serialize for an object. Below are some tips you may use for rushing up the marshaling and un-marshaling of items for the duration of Java serialization system.
Mark the undesirable or non Serializable attributes as transient. This is a straight forward gain considering your attributes for serialization are without a doubt marked and can be without difficulty performed the usage of Serialzable interface itself.
Save most effective the kingdom of the object, not the derived attributes. Some times we keep the derived attributes as part of the object however serializing them can be costly. Therefore recollect calcualting them in the course of de-serialization technique.
Serialize attributes simplest with NON-default values. For examples, serializing a int variable with price zero is just going to take extra area however, choosing not to serialize it'd prevent quite a few performance. This technique can avoid a few types of attributes taking unwanted space. This would require use of Externalizable interface when you consider that characteristic serialization is decided at runtime primarily based on the cost of every characteristic.
Use Externalizable interface and put in force the readExternal and writeExternal techniques to dynamically identify the attributes to be serialized. Some times there can be a custom common sense used for serialization of numerous attributes.
Question 35. What Is A Serial Version Uid (serialversionuid) And Why Should I Use It? How To Generate One?

Answer :

The serialVersionUID represents your magnificence model, and you ought to exchange it if the present day version of your elegance isn't backwards well matched with its earlier variations. This is extract from Java API Documentation

The serialization runtime associates with every serializable elegance a model number, known as a serialVersionUID, which is used all through deserialization to verify that the sender and receiver of a serialized item have loaded instructions for that item that are compatible with admire to serialization.

Most of the instances, we probable do not use serialization without delay. In such instances, I would suggest to generate a default serializable uid via clicking the fast fix choice in eclipse.

Question 36. What Would Happen If The Serialversionuid Of An Object Is Not Defined?

Answer :

If you do not outline serialVersionUID for your serilizable elegance, Java compiler will make one through developing a hash code the use of maximum of your magnificence attributes and features. When an object receives serialized, this hash code is stamped on the object that is called the SerialVersionUID of that item. This ID is needed for the model control of an object. SerialVersionUID may be targeted within the class report additionally. In case, this ID is not distinct by you, then Java compiler will regenerate a SerialVersionUID based on up to date magnificence and it'll not be viable for the already serialized elegance to recover whilst a class field is brought or modified. Its endorsed which you always declare a serialVersionUID for your Serializable training.

Java-Springs Interview Questions
Question 37. Does Setting The Serialversionuid Class Field Improve Java Serialization Performance?

Answer :

Declaring an express serialVersionUID area to your training saves some CPU time only the first time the JVM method serializes a given Class. However the advantage isn't always enormous, In case when you have not declared the serialVersionUID its fee is computed by way of JVM once and ultimately kept in a gentle cache for future use.

Question 38. What Are The Alternatives To Serialization? If Serialization Is Not Used, Is It Possible To Persist Or Transfer An Object Using Any Other Approach?

Answer :

In case, Serialization isn't always used, Java gadgets can be serialized through many ways, a number of the popular strategies are listed beneath:

Saving item kingdom to database, this is maximum commonplace method used by most programs. You can use ORM tools (e.G. Hibernate) to shop the gadgets in a database and examine them from the database.
Xml based totally information switch is any other popular mechanism, and quite a few XML primarily based internet services use this mechanism to switch records over network. Also loads of equipment save XML files to persist data/configurations.
JSON Data Transfer - is currently famous statistics transfer format. A lot of web services are being advanced in JSON due to its small footprint and inherent integration with internet browser due to JavaScript layout.
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 now not be serialized. Once the manner of de-serialization is achieved, the temporary variables do not undergo a exchange and retain their default fee. Marking unwanted fields as brief assist you to boost the serialization overall performance. Below is a easy instance where you may see the usage of brief key-word.

 Elegance MyVideo implements Serializable

    personal Video video;

    private brief Image thumbnailVideo;

    private void generateThumbnail()

    

        // Generate thumbnail.

    

 Personal void readObject(ObjectInputStream        inputStream)

            throws IOException, ClassNotFoundException

    

        inputStream.DefaultReadObject();

        generateThumbnail();

        

Question 40. Why Does Serialization Not Save The Value Of Static Class Attributes? Why Static Variables Are Not Serialized?

Answer :

The Java variables declared as static aren't taken into consideration part of the state of an object when you consider that they are shared via all instances of that magnificence. Saving static variables with each serialized item might have following troubles.

It will make redundant reproduction of equal variable in a couple of gadgets which makes it in-green.
The static variable may be changed by using any item and a serialized reproduction could be stale or now not in sync with contemporary fee.
JMS(Java Message Service) Interview Questions
Question 41. How To Serialize A Collection In Java? How To Serialize A Arraylist, Hashmap Or Hashset Object In Java?

Answer :

All widespread implementations of collections List, Set and Map interface already implement java.Io.Serializable. All the generally used collection classes 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 approach you do not actually need to put in writing anything precise to serialize collection gadgets. However you need to hold following matters in thoughts earlier than you serialize a collection object - Make positive all the items introduced in collection are Serializable. - Serializing the collection may be steeply-priced therefore make sure you serialize simplest required data isntead of serializing the whole series. - In case you're using a custom implementation of Collection interface then you could want to put in force serialization for it.

Question forty two. Is It Possible To Customize The Serialization Process? How Can We Customize The Serialization Process?

Answer :

Yes, the serialization system may be customized. When an object is serialized, objectOutputStream.WriteObject (to save this object) is invoked and while an object is read, ObjectInputStream.ReadObject () is invoked. What most of the people do not know is that Java Virtual Machine affords you with an option to define these strategies as in step with your needs. Once that is performed, these two methods can be invoked via the JVM rather than the software of the default serialization manner. Classes that require unique managing at some stage in the serialization and deserialization procedure have to enforce unique techniques with those exact signatures:

non-public void writeObject(java.Io.ObjectOutputStream out)

     throws IOException

 private void readObject(java.Io.ObjectInputStream in)

     throws IOException, ClassNotFoundException;

 non-public void readObjectNoData() 

     throws ObjectStreamException;

Java applet Interview Questions
Question forty three. How Can A Sub-class 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?

Answer :

In Java, if the exquisite magnificence of a category is enforcing Serializable interface, it means that it is already serializable. Since, an interface can't be unimplemented, it isn't always viable to make a class non-serializable. However, the serialization of a new elegance may be averted. For this, writeObject () and readObject() techniques must be implemented on your class in order that a Not Serializable Exception can be thrown by way of those techniques. And, this may be accomplished through 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 now not serialize this class”);

 non-public void readObject(java.Io.ObjectInputStream in)

     throws IOException, ClassNotFoundException 

 throw new NotSerializableException(“Can not serialize this elegance”);

non-public void readObjectNoData() 

     throws ObjectStreamException; 

 throw new NotSerializableException(“Can no longer serialize this magnificence”);

Question 44. What Changes Are Compatible And Incompatible To The Mechanism Of Java Serialization?

Answer :

This is one among a hard and problematic questions and answering this correctly could suggest you're an expert in Java Serialization idea. In an already serialized item, the maximum hard challenge is to trade the structure of a category whilst a new field is introduced or removed. As in step with the specs of Java Serialization, addition of any technique or subject is considered to be a well matched trade whereas converting of class hierarchy or non-implementation of Serializable interface is taken into consideration to be a non-compatible alternate. You can undergo the Java serialization specification for the significant list of well suited and non-compatible changes. If a serialized item want to be like minded with an older version, it is important that the more moderen version follows a few regulations for like minded and incompatible adjustments. A like minded alternate to the enforcing class is one that can be implemented to a new version of the magnificence, which nevertheless keeps the item circulate well suited with older version of identical class.

Some Simple Examples of well matched changes are:

Addition of a brand new field or class will now not have an effect on serialization, on the grounds that any new information in the circulation is absolutely overlooked by way of older variations. The newly delivered subject could be set to its default values while the item of an older model of the class is un marshaled. 
The get right of entry to modifiers change (like personal, public, included or default) is well suited when you consider that they're not contemplated in the serialized item circulation.
Changing a brief subject to a non-temporary area is well suited exchange in view that it's far just like adding a field.
Changing a static subject to a non-static subject is compatible change because it is also much like including a subject.
Some Simple Examples of incompatible modifications are:

Changing implementation from Serializable to Externalizable interface can't be executed due to the fact this will result in the creation of an incompatible item stream.
Deleting a current Serializable fields will cause a trouble.
Changing a non-brief field to a temporary field is incompatible alternate seeing that it's miles just like deleting a area.
Changing a non-static area to a static discipline is incompatible alternate on the grounds that it's also similar to deleting a subject.
Changing the form of a characteristic inside a class might be incompatible, since this will cause a failure when attempting to examine and convert the original area into the new field.
Changing the bundle of class is incompatible. Since the absolutely-qualified class call is written as a part of the 
Java serialization is one of the most generally misunderstood areas. Many builders still think its handiest used for saving gadgets on the record device.

Hope you located this list beneficial. Can you observed of a questions that is not a part of this list? Please take into account to percentage it with me in remarks section & I will try to include it in the listing.




CFG