Serialization in java(interview questions)

Question 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 provides Serialization API for serializing and deserializing object which includes java.io.Serializable, java.io.Externalizable, ObjectInputStream and ObjectOutputStream etc. Java programmers are free to use default Serialization mechanism which Java uses based upon structure of class but they are also free to use there own custom binary format, which is often advised as Serialization best practice, Because serialized binary format becomes part of Class’s exported API and it can potentially break Encapsulation in Java provided by private and package-private fields. This pretty much answer the question What is Serialization in Java.

Question 2: How to make a Java class Serializable?

Making a class Serializable in Java is very easy, Your Java class just needs to implements java.io.Serializable interface and JVM will take care of serializing object in default format. Decision to making a Class Serializable should be taken concisely because though near term cost of making a Class Serializable is low, long term cost is substantial and it can potentially limit your ability to further modify and change its implementation because like any public API, serialized form of an object becomes part of public API and when you change structure of your class by implementing addition interface, adding or removing any field can potentially break default serialization, this can be minimized by using a custom binary format but still requires lot of effort to ensure backward compatibility. One example of How Serialization can put constraints on your ability to change class is SerialVersionUID. If you don’t explicitly declare SerialVersionUID then JVM generates its based upon structure of class which depends upon interfaces a class implements and several other factors which is subject to change. Suppose you implement another interface than JVM will generate a different SerialVersionUID for new version of class files and when you try to load old object object serialized by old version of your program you will get InvalidClassException.

 

Question 3: What is the difference between Serializable and Externalizable interface in Java?

Answer:  This is most frequently asked question in Java serialization interview. Here is my version Externalizable provides us writeExternal() and readExternal() method which gives us flexibility to control java serialization mechanism instead of relying on Java’s default serialization. Correct implementation of Externalizable interface can improve performance of application drastically.

SERIALIZABLE
EXTERNALIZABLE
Methods
It is a marker interface it doesn’t have any method.
It’s not a marker interface.
It has method’s called writeExternal() and readExternal()
Default Serialization process
YES, Serializable provides its own default serialization process, we just need to implement Serializable interface.
NO, we need to override writeExternal() and readExternal() for serialization process to happen.
Customize serialization process
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.
Serialization process is completely customized
We need to override Externalizable interface’s writeExternal() and readExternal() methods.
Control over Serialization
It provides less control over Serialization as it’s not mandatory to define readObject() and writeObject() methods.
Externalizable provides you great control over serialization process as it is important to override  writeExternal() and readExternal() methods.
Constructor call during deSerialization
Constructor is not called during deSerialization.
Constructor is called during deSerialization.

Question 4: How many methods Serializable has? If no method then what is the purpose of Serializable interface?

Answer: Serializable interface exists in java.io package and forms core of java serialization mechanism. It doesn’t have any method and also called Marker Interface in Java. When your class implements java.io.Serializable interface it becomes Serializable in Java and gives compiler an indication that use Java Serialization mechanism to serialize this object.

Question 5: What is serialVersionUID? What will happen if i do not define it in class?

One of my favorite question interview question on Java serialization. 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. Consequence of not specifying serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. 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.

Question 6: While serializing you want some of the members not to serialize? How do you achieve it?

Another frequently asked Serialization interview question. This is sometime also asked as what is the use of transient variable, does transient and static variable gets serialized or not etc. so if you don’t want any field to be part of object’s state then declare it either static or transient based on your need and it will not be included during Java serialization process.

Question 7: What will happen if one of the members in the class doesn’t implement Serializable interface?

Answer: 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.

Question 8: If a class is Serializable but its super class in not, what will be the state of the instance variables inherited from super class after deserialization?

Answer: When we deserialize the object.

If superclass has implemented Serializable – constructor is not called during DeSerialization process.

If superclass has not implemented Serializable – constructor is called during DeSerialization process.

Java serialization process only continues in object hierarchy till the class is Serializable i.e. implements Serializable interface in Java and values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process. Once the constructor chaining will started it wouldn’t be possible to stop that , hence even if classes higher in hierarchy implements Serializable interface , there constructor will be executed. As you see from the statement this Serialization interview question looks very tricky and tough but if you are familiar with key concepts its not that difficult.

You can try writing a program for both the cases which has super class as serializable and not serializable.

Question 9: Can you Customize Serialization process or can you override default Serialization process in Java?
Answer: 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. In my opinion this is one of the best question one can ask in any Java Serialization interview, a good follow-up question is why should you provide custom serialized form for your object?

Question 10:Suppose super class of a new class implement Serializable interface, how can you avoid new class to being serialized?
Answer: Using the custom serialization you can provide definition of writeObject method where you can throw NotSerializableException.

Question 11: Which methods are used during Serialization and DeSerialization process in Java?
Answer: Java Serialization is done by java.io.ObjectOutputStream class. That class is 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. Call to writeObject() method trigger serialization process in java. one important thing to note about readObject() method is that it is used to read bytes from the persistence and to create object from those bytes and its return an Object which needs to be type cast to correct type.

Question 12: Suppose you have a class which you serialized it and stored in persistence and later modified that class to add a new field. What will happen if you deserialize the object already serialized?
Answer: This will depend upon if you have defined the static final serialVersionUID. If it is not defined then for each object a serialVersionUID is generated based on the hashCode of this object.In that case if you add new fields and then you try to deserialize the object then there will be InvalidClassException and if we have defined the serialVersionUID then there will be no issues.

Question 13: Why static member variables are not part of java serialization process (Important)?

Answer: Serialization is applicable on the instance variable which are either objects or primitives. As static variable are class level variable they doesn’t exists at instance level so, they are not part of serialized object.

Question 14: What will happen if one the member of class does not implement Serializable interface (Important)?

Answer: NotSerializableException will be thrown.

Question 15: What will happen if we have used List, Set and Map as member of class?

Answer: These collection classes implements serializable so it will work fine.

Question 16:Is constructor of class called during DeSerialization process?

Answer: It depends on whether our object has implemented Serializable or Externalizable.

If Serializable has been implemented – constructor is not called during DeSerialization process.But, if Externalizable has been implemented – constructor is called during DeSerialization process.

Question 17: Is constructor of super class called during DeSerialization process of subclass (Important)?

Answer: It is depends on whether our superclass has implemented Serializable or not.

If superclass has implemented Serializable – constructor is not called during DeSerialization process.
If superclass has not implemented Serializable – constructor is called during DeSerialization process.
Question 18: How you can avoid Deserialization process creating another instance of Singleton class (Important)?

Answer:

We can simply use readResove() method to return same instance of class, rather than creating a new one.


Defining readResolve() method ensures that we don’t break singleton pattern during DeSerialization process.
 
 private Object readResolve() throws ObjectStreamException {
      return instance;
 }


Also define readObject() method:
 private void readObject(ObjectInputStream ois) throws IOException,ClassNotFoundException{
       ois.defaultReadObject();
       synchronized (SingletonClass.class) {
        if (instance == null) {
              instance = this;
        }
       }
 }

Exception handling in multi-threading in java

In my recent project i need to handle the exception in case of multiple thread. As Thread run in parallel and simply putting a try/catch around thread.start() would not help much. So, here is the solution. Thread has nested class named “UncaughtExceptionHandler” which can be used in much better way to handle exceptions.

Other way around could be to just put try/catch in run method of Thread but better way would be handle the exception in callback way explained above.

Thanks!!!

Mysql like AES_ENCRYPTION and AES_DECRYPTION in groovy/Java

In my recent project there was a requirement of encrypting the data in Database but same was needed in the application level as well so at the mysql end i used AES_encryption() and AES_decryption().

e.g.

and in the Groovy/Grails/Java (application end) same can be achieved using the following code :

The main thing to note in the code given above is that for encryption first you need to encrypt data and then apply hex and in case of decryption unhex the data and then decrypt the same.

The main thing to note in the code given above is that for encryption first you need to encrypt data and then apply hex and in case of decryption unhex the data and then decrypt the same.

This helps me hope that helps you guys!!!

Thanks,

Anuj Aneja

Using custom tag for embedding the video in grails

I had to make a video available on my gsp page. So I looked at the grails flash-player plugin. After going through the documentation I found that it could not be used with videos on Youtube. This code given below will generate the script for the flash player on your gsp for playing youtube videos.

This is the general code for a youtube video. URL in the browser for video looks like -http://www.youtube.com/watch?v=YG9RGKYauhE&feature=related.The common thing between embed code and URL of video is the key for the video which uniquely identifies it.So copy and paste the code of the in your gsp page and pass the video key to change the video as you want. But to make it simple I made a custom tag like–

so you just need to write the following tag which will set its default height,width etc.

I hope it helps you guys!!!

Anuj Aneja