JavaRush /Java Blog /Random EN /Top 13 questions about serialization in interviews
Dmitry Vasilyev
Level 26
Саратов

Top 13 questions about serialization in interviews

Published in the Random EN group
Translation of the article https://javarevisited.blogspot.com/2011/04/top-10-java-serialization-interview.html What is serialization in Java? Serialization is one of the important concepts that is quite rarely used as a solution to save the state of programs and therefore this API is often overlooked by developers. However, in my experience, serialization is a pretty important topic in any basic Java interview. Almost every interview I've encountered has one or two questions about serialization, and I've seen candidates feel uncomfortable about their lack of experience in this area after a few questions on this topic. They do not know how to serialize an object in Java, they are not familiar with any examples of serialization and cannot explain the mechanics of its work, the difference between a transient and a volatile variable, they do not know how many methods the Serializable interface has. What is a marker interface? What is its purpose? What is the difference between Externalizable and Serializable implementation in Java? Why didn’t java replace Serializable with @Serializable after introducing the annotation? In this article, we will cover questions for both beginners and advanced developers, which can be equally useful for everyone: from juniors to senior developers. Most commercial projects use either databases, memory-mapped files , or just plain flat files to provide greater robustness, but few rely on Java's serialization process. In any case, this post is not a tutorial - it is rather about questions that are worth clarifying for yourself before going to any Java interview and being surprised by terms unknown to yourself. For those who are not familiar with Java serialization at all: “Serialization in Java is a process that is used to serialize an object in Java by storing the state of the object in a file with a .ser extension and recreating the state of the object from this file. This reverse process is called deserialization. sepulka The Java Serialization API provides developers with a standard mechanism for serializing objects using the Serializable and Externalizable interfaces. By the way, this article is a continuation of my ( not mine, the translator, but the author of the English original) previous articles: 20 interview questions on design patterns and 10 interview questions on the Singleton pattern in Java . So, let's go! What is serialization in Java? Object serialization in Java is a process used to convert an object into a binary format that can be saved to disk or sent over the network to any other running Java virtual machine; the reverse process of creating an object from a binary stream is called deserialization. Java provides an API which includes java.io.Serializable, java.io.Externalizable, ObjectInputStream and ObjectOutputStream etc. Programmers are free to use the default serialization mechanism that Java uses based on the class structure, but they can also use their own custom binary format, which is often recommended as a serialization best practice because the serialized binary format becomes part of the class's exported API and can potentially break encapsulation in Java provided by private and package-private fields. In general, this information will be quite enough to get started. How to make a Java class serializable? It is very easy. Your class simply needs to implement the java.io.Serializable interface and the JVM will take care of serializing the object in a default format. The decision to create a serializable class should be made briefly because, although the short-term costs of creating a serializable class are low, the long-term costs are significant and can potentially limit your ability to make further modifications to the implementation. This happens because, like any public API, the serialized form of an object becomes part of the public API, and when you change the structure of your class by implementing an add interface, adding or removing any field can potentially break the default serialization. However, this can be minimized by using a custom binary format, but it still requires a lot of effort to ensure backward compatibility. One example of how serialization can limit your ability to modify a class is the SerialVersionUID field. If you don't explicitly declare the SerialVersionUID, then the virtual machine generates it based on the class structure, which depends on the interfaces implemented by the class and several other factors that can be changed. Let's say you implement a different interface as opposed to the JVM, which will generate a different SerialVersionUID for the new version of the class files, and when you try to load an old object serialized by the old version of your program, you will get an InvalidClassException. Question 1) What is the difference between Serializable and Externalizable interface in Java? This is the most frequently asked Java serialization interview question. The Externalizable interface provides us with writeExternal() and readExternal() methods, which give us the flexibility to control serialization instead of relying on the default mechanism. Proper implementation of the Externalizable interface can significantly improve application performance. Question 2) How many methods does Serializable have? If there is no method, then what is the purpose of the Serializable interface? The serializable interface exists in the java.io package and forms the core of Java's serialization engine. It does not have any methods and is also called marker interface in Java. When your class implements the java.io.Serializable interface, it becomes serializable. It's simple. Question 3) What is serialVersionUID? What happens if you don't define it? One of my favorite Java serialization interview questions. SerialVersionUID is an identifier that is put on an object when it is serialized, usually a hash code of the object. You can use the serialver tool to get the serialVersionUID of the serialized object. SerialVersionUID is used for object version control. You can also specify serialVersionUID in your class file manually. The consequence of not specifying serialVersionUID is that if you add or change any field in a class, the already serialized class will not be able to recover because the serialVersionUID generated for the new class will be different from the same field of the old serialized object. The Java serialization process relies on the correct serialVersionUID to restore the state of the serialized object and throws a java.io.InvalidClassException if there is a mismatch. To learn more about serialversionuid, see here . Question 4) When serializing, do you want some members not to be serialized? How to achieve this? Another frequently asked serialization interview question. Sometimes people also ask how a transient variable is used, whether a transient and a static variable is serialized or not, etc., so if you don't want any field to be part of the object's state, declare it as static or transient depending on your needs, and it will not be included in the Java serialization process. Question 5) What happens if one of the class members does not implement the Serializable interface? One of the simple questions about serialization process in Java. If you try to serialize an object of a class that implements Serializable, but the object includes a reference to a class that is not Serializable, then a NotSerializableException will be thrown at runtime, and that's why I always put a SerializableAlert (comments section in my code), one of the best code commenting techniques is to instruct the developer to remember this fact when adding a new field to the Serializable class. Question 6) If a class is serializable but its superclass is not, what will be the state of the instance variables inherited from the superclass after deserialization? The Java serialization process continues only in the object hierarchy as long as the class implements the Serializable interface and the values ​​of variables inherited from the superclass will be initialized by calling the non-serializable superclass's constructor during the deserialization process. Once the constructor chain has started, there is no way to stop it, so even if classes higher in the hierarchy (do not) implement the Serializable interface , the constructor will be executed. This serialization interview question may seem very difficult, but if you are familiar with the key concepts, it will not be difficult. Question 7) Can you customize the serialization process or override the default serialization process in Java? The answer is yes, you can. We all know that to serialize an object, ObjectOutputStream.writeObject(saveThisObject) is called and to read an object, ObjectInputStream.readObject() is called, but there is one more thing that the Java Virtual Machine provides you with - defining these two methods in your class. If you define them in your class, the JVM will call these two methods instead of using the default serialization mechanism. Here you can configure the object's serialization and deserialization behavior by performing any preprocessing or postprocessing task. It is important to note that these methods must be private to avoid inheritance, overriding, or overloading. Since only the Java Virtual Machine can call a private method, the integrity of your class will be preserved and serialization will work as usual. In my opinion, this is one of the best questions that can be asked in any Java Serialization interview. A good follow-up question is: why would you need to provide a custom serialized form for your object? Question 8) Suppose the superclass of a new class implements the Serializable interface, how can we avoid serializing the new class? One of the difficult interview questions on Serialization in Java. If the superclass of a class already implements the Serializable interface in Java, then the descendant class is also Serializable, since you can't not implement the parent's interface, and it's not really possible to make it a Non Serializable class. However, there is a way to avoid serialization for this new class. To do this, you need to implement the writeObject() and readObject() methods and throw NotSerializableException from these methods. This question is usually asked as an additional question as the interview progresses. Question 9) What are the methods used in the serialization and deserialization process in Java? This is a very common question in serialization. What is the interviewer trying to find out in this case? Whether you are familiar with the use of readObject(), writeObject(), readExternal() and writeExternal() or not. Java serialization is done by the java.io.ObjectOutputStream class. This class is a filtered stream that is wrapped around a lower level byte stream to handle the serialization engine. To save any object using the serialization mechanism, we call ObjectOutputStream.writeObject(saveThisObject) and to deserialize that object, we call the ObjectInputStream.readObject() method. Calling the writeObject() method starts the serialization process. One important thing to note about the readObject() method is that it is used to read bytes and to create and return an object from those bytes, which in turn must be cast to the correct type. Question 10) Suppose you have a class that you have serialized and saved, and then you modify that class to add a new field. What happens if you deserialize an already serialized object? It depends on whether the class has its own serialVersionUID or not. As we know from the above questions, if we don't provide serialVersionUID in our code, the java compiler will generate it itself and usually it will be equal to the hash code of that object. After adding any new field, there is a chance that the new serialVersionUID generated for that version of the class does not match the already serialized object, in which case the API will throw a java.io.InvalidClassException. For this reason, it is recommended to have your own serialVersionUID in your code, which is always the same for the same class. Question 11) What are the compatible and incompatible changes in the Java serialization mechanism? The real problem is changing the structure of classes by adding any field, method or removing any field or method with an already serialized object. According to the Java Serialization specification, adding any field or method comes under compatible change and changing. class hierarchy or UN-implementing Serializable interfaces some under non compatible changes). For a complete list of compatible and incompatible changes, I would suggest reading the Java Serialization Specification. Question 12) Can we transfer a serialized object over the network? Yes, you can pass a serialized object over the network because a Java serialized object is a collection of bytes that can be passed around in any way. You can also store the serialized object on disk or in a database as a Blob. Question 13) What types of variables are not serialized during Java serialization? This question has sometimes been asked differently, but the goal is the same: to find out whether a Java developer knows the specifics of serializing static and transient variables. Since static variables belong to a class and not an object, they are not part of the object's state, so they are not persisted during the Java serialization process. Because Java serialization only stores the state of an object and not the object itself, transient variables are also not included in the serialization process and are not part of the object's serialized state. After this question, perhaps the interviewer will ask: If you do not store the values ​​of these variables, then what will the value of these variables be after deserializing and recreating this object? And this, colleagues, think for yourself :) The original article is here .
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION