Programs

Java Serialization Interview Questions & Answers [For Beginners & Experienced]

Java is one of the better programming languages out there in the world. We have been fortunate enough to see Java develop over time and become the massively popular language we know it as today. These improvements, which were made in Java, led to the inclusion of some really crucial features that define how we write programs today. One of those features is Serialization.

In its essence, serialization is just a mechanism used to store an object into the memory. So, when we say we are serializing an object, we mean that we are converting the object in question from the state, which it was into a stream of bytes. This conversion from its native state to the byte stream makes writing this object to a file a breeze.

This file can then be transported anywhere we wish, and to access the object and its features, all we need to do is de-serialize the object. De-serialization, as the name suggests, is the opposite of serialization. Here, we convert the byte’s stream into the native state of the object to use the object. 

Check out our free courses to get an edge over the competition.

Serialization enables developers to write their code with a certain level of flexibility. The ability to take the object and use it with its native property elsewhere is crucial in today’s workflow. No wonder recruiters want their potential employees to know more about object serialization in java.

Whether you have used serialization in your projects or not, you cannot merely let the importance of it slide. So, to aid you in your endeavor of becoming a professional java developer, we have collected some fascinating java serialization interview questions, which you will find below.

Java Serialization Interview Questions

Q1. What do you mean by Serialization in the context of Java programming language?

Ans. The definition of serialization is perhaps the most basic yet one of the most frequently asked questions in the context of Java serialization. You will have to answer this question is almost all the interviews. Hence, you must have a good definition of Java serialization instilled in your mind. So, serialization is nothing but how an object written in Java is converted into a bytes stream.

Check out upGrad’s Advanced Certification in Blockchain

The main objective of this is to enable the object to be transferred to another machine or to save the state of the object into a file or save the object’s state into a database. Once the object is successfully serialized, then we could quickly obtain the object back into its former glory by merely de-serializing the object. 

Q2. What is the way in which we can serialize an object in Java? Write a program to serialize and de-serialize the object.

Ans. In an interview, if you are able to augment your theoretical knowledge with the ability to write a program, the chances of your selection automatically increase. It is also given that in any interview, you will be tasked to write a basic program (at the very least a basic program), which demonstrates how serialization and de-serialization occurs. Before you go and write this program yourself, you need to remember one key thing about object serialization in java.

To serialize an object, you would need to write the object that uses the class java.io.Serializable interface. You need to make sure that you are using a Marker interface for the class’s object, which you want to serialize. Meaning the class in question should not have any written methods in the class. This class also needs to tell the Java Virtual Machine that the ensuing object will have to change forms and shape a stream of bytes. 

Check out upGrad’s Advanced Certification in Cyber Security

The code for serialization is written below. 

OutputStream fout = new FileOutputStream(“ser.txt”);

ObjectOutput oout = new ObjectOutputStream(fout);

System.out.println(“Serialization process has started, serializing employee objects…”);

oout.writeObject(object1);

The code for de-serialization is written below.

InputStream fin=new FileInputStream(“ser.txt”);

ObjectInput oin=new ObjectInputStream(fin);

System.out.println(“DeSerialization process has started, displaying employee objects…”);

Employee emp;

emp=(Employee)oin.readObject();

Explore our Popular Software Engineering Courses

Learn: Memory Allocation in Java: Everything You Need To Know

Q3. What is the difference between the interfaces for Serialization and Externalizable?

Ans. This question could mean the difference between you getting selected for the job or not. Suppose you manage to answer this question in a very comprehensive manner. In that case, the interviewer is bound to be impressed with your knowledge of this subject, and the chances of your selection for the job will automatically skyrocket. You will find all the critical differences in the table below: 

The properties on which we are comparing both of these methods.
SERIALIZABLE
EXTERNALIZABLE
Methods which are present in the classes of these two different interfaces This happens to be a marker interface. Marker interfaces cannot have any member functions. They have to be empty except that they need to have an instruction present in them, which tells the Java Virtual Machine that this class’s object has to be converted into a stream of bytes. This is not a maker interface meaning it has some member methods. 

It has method’s called writeExternal() and readExternal() 

What is their default way of serialization?  For serializable, you will find a default way in which you can serialize the objects which you write. All you would need to do as a programmer would be to find a way in which you can integrate this interface into your program. You will not find a default way in which you can implement serialization. You will need to write your own methods or override the existing ones.
What is the way in which they implement the process of serialization?  You can customize the way in which serialization is implemented in this interface. However, you cannot override the existing methods. You will need to implement these methods into your own class to obtain the degree of freedom you desire.   In this method, you would need to override the default methods. So if you want to implement a customized way to serialize the object, you should choose this interface over the default way of Serializable.
What is the degree of control which they offer in the process of serialization,  You will find a tiny wiggle room when you are using this interface. You also need to write the default functions into your class to get the most out of this method. However, it is not compulsory for you to do so, meaning you will still be able to serialize objects with this interface without writing the default functions into your custom class.  This interface provides excellent control over the entire process. For that reason alone, if you are using this interface, it will be compulsory for you to write the two methods into your custom class.
What is the constructor used while using de-serialization,  There is no constructor which is called during the process of serialization. There is a call made to the contractor when serializing the objects using this interface.

Q4. Write a program in which you implement the custom process of serialization and de-serialization.

Ans. Here comes the tricky part. This is the question through which you can show all the previous question knowledge through a practical use case scenario. The ability for you to be able to write these programs will clearly demonstrate your expertise and help you get the job you want. 

Written below you will find the custom way of writing the writeObject() method.

 private void writeObject(ObjectOutputStream os) {

          System.out.println(“In, writeObject() method.”);    

          try {

                 os.writeInt(this.id);

                 os.writeObject(this.name);

          } catch (Exception e) {

                 e.printStackTrace();

          }

   } 

Written below you will find the custom implementation of de-serliasation.

private void readObject(ObjectInputStream ois) {

          System.out.println(“In, readObject() method.”);

          try {

                 id=ois.readInt();

                 name=(String)ois.readObject();

          } catch (Exception e) {

                 e.printStackTrace();

          }

   } 

Explore Our Software Development Free Courses

Q5. How will you implement Serialisation and de-serialization using the Externalizable interface?

Ans. To implement serialization and de-serialization using the externalizable interface, you will need to write the function writeExternal() and readExternal() on your own. You will find the code for both written below.

Customizing the writeExternal() method

  public void writeExternal(ObjectOutput oo) throws IOException {

          System.out.println(“in writeExternal()”);

          oo.writeInt(id);

          oo.writeObject(name);

  }

Customizing the readExternal() method

public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {

          System.out.println(“in readExternal()”);

          this.id=in.readInt();

          this.name=(String)in.readObject();

  }

In-Demand Software Development Skills

Read about: Python vs Java in 2020: Which One You Should Choose?

Q6. Let us say that you do not want a specific variable to be serialized. What will you do to prevent the member variables which you do not wish to be serialized?

Ans. It is a highly conceptual question. You need to have knowledge of static and non-static variables to be able to answer this question quickly. Suppose you want a particular variable not to get serialized. In that case, you will have to make them static since any static variable’s value cannot be changed, and hence because of this reason, they will also not get serialized. 

Q7. What do you mean by serialVersionUID?

Ans. For every class which we want to be serialized, they would be given a class number. This number, which is given to every class, which is to be serialized, is called a serialVersionUID. This ID is essential because, at the time of getting back the object in its native form, the Java Virtual Machine looks out for the ID, which is associated with the object.

Then it quickly refers to the ID of the classes which were supposed to be serialized. When it finds the corresponding class to which this object belongs, the de-serialization process begins. 

Q8. Let us say that we forgot to mention or define the serialVersionUID. What will be the impact of this action on the program which we have written?

Ans. This question is another fundamental question. You would need a piece of sound knowledge to be able to answer this question correctly. The first thing we need to clarify is that serialVersionUID is used to do version control of the object in the question. Let us say there is no ID defined for the class, so the Java compiler would not know which class the object belongs to. At the run time or when you are serializing the object, there will not be any errors because there is no need per se of any ID to be defined.

However, when we want the data stream to be converted into the object, then the Java compiler will throw an error. The compiler will not know which class the object belongs to, and hence it will not be able to find and connect all the member functions and the variables which are associated with this object. Because the compiler will be stuck in this step, it will throw an error of serialVersionUID mismatch (java.io.InvalidClassException).

Q9. In case we cannot serialize, or the method of serialization is not available, is there any other method by which we would be able to transfer the object that we wrote over a network?

Ans. There are a few methods in which we would be able to transfer the object that we wrote over a network. You will find some of them listed below.

  1. You can try to convert the object into a JSON file. It is not that difficult to convert the object into a JSON string, and when you have written the JSON file, conversion of it to the code file is also not very difficult. So, you can transfer the JSON string, which you wrote over the network.
  2. You can also use the Hibernate tool (this is an ORM tool). This tool allows the object to persist in the database. Then the object which is written can also be very easily read later on.
  3. You can also use the technology of XML. You can try to convert the object into an XML file, and then you can quickly transfer that file via the network.

Must Read: Top 24 Java Interview Questions & Answers

Read our Popular Articles related to Software Development

Wrapping up

If you’re interested to learn more about Java, OOPs & full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

What are the benefits of using bootstrap?

Bootstrap is a front-end framework that provides a library of CSS and JavaScript components for developing responsive, mobile-first websites. It offers a wide range of features, including grid system, typography, components, and JavaScript plugins. Bootstrap also offers a responsive design that adapts to different screen sizes, making it an ideal choice for developing websites for mobile devices. It also has a large community of developers who can provide support and assistance. Similarly, there are many online resources, such as tutorials and templates, that can help you get started with Bootstrap.

What is the difference between design and development?

Web design is the process of creating a graphical interface for a website. This interface includes the layout of the website, the colors used, the fonts, and the images. Web development is the process of creating the functionality of a website. This includes the code that makes the website work, the databases that store the data, and the scripts that run the website. It is important to note that web design and web development are two separate disciplines. A web designer is not necessarily a web developer and vice versa. Web design is focused on the look and feel of the website, while web development is focused on the functionality of the website.

How can I use PHP to improve architectural firms?

PHP is a server-side scripting language built for web development. However, it is also used as a general-purpose programming language. PHP code is inserted into the HTML of a web page to create dynamic web content. PHP can be used to improve architectural firms by helping with the organization of projects, creating drafts and models of buildings, and helping with the creation of blueprints. Additionally, PHP can be used to manage client information and track payments. It can also be used to create a website for the architectural firm that can showcase their work. Similarly, a blog could be added to the website to provide updates on the latest projects and news within the architectural field.

Want to share this article?

Prepare for a Career of the Future

INDUSTRY TRUSTED LEARNING - INDUSTRY-RECOGNIZED CERTIFICATION.
Enroll Today

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks