Top 55 Java Interview Questions and Answers

Top 55 Java Interview Questions and Answers


This blog provides a comprehensive overview of Java programming, spanning various aspects from its popularity and versatility to its application in J2EE web development and Android app development. It delves into frequently asked Java interview questions, covering Java basics, Servlets, Java JDBC, JPA, Hibernate, Spring MVC, and Spring Boot. The article offers insights into crucial topics such as platform independence, Java frameworks, and database interactions. It emphasizes the significance of understanding fundamental concepts and provides valuable tips for mastering Java technologies. Whether you're a beginner or seeking to enhance your expertise, this blog serves as a valuable guide for navigating the diverse world of Java programming.

Java continues to be one of the most popular languages for developing J2EE Web Applications. Not only J2EE but Java is also used to develop Android applications too.

Right from Java’s introduction to the Information Technology industry, it has been a leader among programming languages. It supports multiple technologies and Frameworks like Servlets, Hibernate and Spring, Spring MVC, and Spring Boot (a hotcake in the market). On the professional front, a Java developer has very good career prospects. Today we have hand-picked some of the most frequently asked questions in a Java job interview. We have segregated the questions based on Frameworks. Let’s explore!

Java Basics

1. What happens if the main method does not have a static modifier?

Missing static modifier is not a compiler error (program compiles successfully). It is a runtime error; the error thrown is “NoSuchMethodError”.

2. What does it mean when we say 'Java is platform-independent?

The code which is written in Java on compiling converts to bytecode (.class). This activity can be performed on any platform (say Windows). This compiled code or bytecode can be run not only on Windows but it can also be run on any platform like Unix/Linux, etc.

3. Explain static functions in Java.

Execution of static functions happens only once and is executed even before the execution of Constructors of a class.

4. Explain the usage of ‘this’ with respect to the constructor in a class.

When the keyword ‘this’ is used in the constructor of a class, we call the concept as Constructor Chaining, in which the execution of one constructor happens from another constructor automatically. 

5. Predict and explain the output of the below program. (a very tricky question in Method Overloading).

public static void function(Integer It){

    System.out.println("method with param type – Integer: "+It);


public static void function(int it){

    System.out.println("method with param type – int: "+ it);



In such a case, the sub-classes are given a high preference over superclasses.

6. What is an ‘instanceOf operator in Java?

It gives the type of an object.

7. What does ‘null’ mean in Java?

When a reference is created and no object is assigned to it, then the reference would point to null.

8. Define a Singleton Class.

A singleton class is a class in which it is possible to create only one object. And this is possible by making the constructor private.

9. Define Association.

Association is a relationship between objects, where there won’t be any owner; thus, making the lifecycle of an object independent of the other.

10. What is the usage of @Override in Java?

The @Override annotation in Java indicates that the child class method is overwriting its base class method.

11. When is Serialization used?

Serialization converts the object state into a byte stream and transmits it over the network. 

12. What are the scripts that are used to start and stop the Tomcat server on Linux?

In Linux env, when the tomcat is installed, we get to see two scripts namely and in the tomcat/bin dir. The main script that starts/shutdown the tomcat server is This is the same script that is called by both and

13. Name some of the new features introduced in Java 8.

Lambda Expressions, Functional Interfaces, Date and Time API, Interface Default Methods, and Static Methods.

14. What are Lambda Expressions?

Lambda Expressions are like functions or a block of code that has no name. The return type and parameter list are optional. The block of code comes into the picture or gets executed when demanded.

Java Servlets

1. Name the most important objects of Servlets, which are used to interact with the client.

HttpServletRequest and HttpServletResponse

2. List out and explain the methods that are used in a Servlet Life Cycle.

In the servlet lifecycle; i.e., from the time of creation till its destruction, a servlet passes through the following methods:

init(); This is the method where the initialization happens for a servlet.
service(); once the initialization is done, the service() method is used to process the request sent by the client
destroy(); the termination of a servlet is done by using the destroy method.

3. Explain HttpServletRequest.

HttpServletRequest is an interface extending another interface, namely ServletRequest. An object of this class receives the request sent by the client. On receiving the request of the client, we can get the data given on a web page using getParameter();

4. What is a Session?

When a user logs into a web application, the time user has spent in the web application is called a Session. 

5. How to create a Session in Servlets?

The HttpSession class is used to create a session reference. And the session can be retrieved by calling the getSession() method of the HttpServletResponse using its object (request)

Ex: HttpSession session = request.getSession();

6. What is ServletContext?

It is ServletConfig available in Javax.servlet.*; package. It is one per class and is created during an initialization process of the servlet. The information about the Web application and container is stored ServletContext object. 

7. What is a Web Container?

A combination of both JSP and Servlet is called Web Container.

8. Explain Servlet Chaining?

It is a sequence of Servlets where a client request is sent to one servlet. The output of this servlet is the input of another servlet, and this continues till the last servlet is encountered. The final output is given to the client as the response. 

9. What is a Cookie in Web terminology?

It is a small storage area in the web browser in which the client information is stored. As the storage space is limited, only strings are stored in a cookie.

10. What is the usage of RequestDispatcher?

The RequestDispatcher is an interface that allows the servlet to dispatch the response (a request after getting processed becomes a response) to another resource like a JSP or a servlet.


1. Explain PreparedStatement.

It is a pre-compiled SQL statement. It makes it easier to set the SQL parameter values dynamically.

2. Name the two packages in which the Date is available and also explain the difference.

The Date types are available in two packages namely (i) Java.sql.Date and (ii) Java.util.Date. The difference between them is, the SQL Date does not hold time whereas the util Date holds time information.

3. What are the two Exceptions that may occur when a database connection fails?

(i): Java.sql.SQLException: bad url or credentials

(ii):Java.lang.ClassNotFoundException: jdbc driver not found in classpath        

4. What is the difference between executeQuery() and executeUpdate()?

executeQuery() is used with select statement and executeUpdate is used with insert/update/delete statements.

5. What are Transactions in JDBC?

A transaction is a work (update, delete, insert) that is done on some data. The work that was done should be either 100% complete (commit) or 0% complete (rollback).

6. What is Database Metadata?

Metadata gives information about the Database. The Connection Object (myConn) is used to call the 'getMetaData()' function; i.e., myConn.getMetaData();

7. What is a CallableStatement? And how do you use it?

CallableStatement in jdbc is used to execute stored procedures. Here is how a stored procedure is invoked and executed with the help of CallableStatement:

    CallableStatement callableStatement = myConn.prepareCall("{call stored_procedure_name()}");         callableStatement.execute();

8. What is Class.forName() used for?

In case of explicit loading of database drivers, the Class.forName() is used. 

9. Describe the types of ResultSet.

Resultset is of three types, namely:

  • TYPE_FORWARD_ONLY: cursor moves forward

  • TYPE_SCROLL_INCENTIVE: cursor moves both forward and backward

  • TYPE_SCROLL_SENSITIVE:  cursor moves both forward and backward but the resultset is sensitive to the changes in the database. The changes could have occurred after the creation of the resultset.

10. What is the advantage of Batch Processing?

When the requirement is to execute several SQL statements in the database, we use Batch Processing, as it reduces the number of interactions with the database; thus, increasing the performance.

JPA and Hibernate

1. Highlight the differences between JPA and Hibernate.

JPA is the specification, and Hibernate is the implementation. 

2. Explain the difference between Hibernate.cfg.xml and Persistence.xml.

Persistence.xml is used to configure the EntityManager; whereas, Hibernate.cfg.xml is used as a source to find the mapping information.

3. Explain Entity in terms of Hibernate?

A POJO (Plain Old Java Object) class can be termed as Entity if an annotation (@Entity) is imported from Javax. persistence. The entity is decorated for a class. An instance of the same class represents a row in a table, and the properties of the class represent a column of the table.

4. What is Persistence Context?

A group of Entities forms a Persistence Context. 

5. How is EntityManager related to Persistence Context?

EntityManager interacts with Persistence Context to update/delete/insert data.

6. Explain Lazy Loading in Hibernate?

In Lazy loading or fetching, if the base class is loaded, the child class is not loaded automatically. Instead, only when needed, the child classes are loaded. 

7. Explain JPQL.

Java Persistence Query Language (JPQL) is also a query language like SQL, by using which the queries can be executed on Entities. 

8. Explain the difference between EntityManager’s persist() and merge().

The persist() method inserts an object of Entity, i.e., row. Whereas, the merge() can do update/insert.

9. What is a SessionFactory in Hibernate?

It is a factory of Session objects (session). The entire Java application is managed with only one SessionFactory object.

10. Differentiate between session.get() and session.load().

When an object is available in the database, use the load method. Whereas the get method is used when we are not sure about the availability of the object.

Spring MVC and Spring Boot 

1. What is Application Context?

Application Context represents the environment in which the Spring application runs. Every application requires configuration, and Application Context helps us in providing that information to the application.

2. What is the advantage of Dependency Injection?

Dependency Injection helps us to make the Java classes independent of each other. This independence (or Dependency Injection) can be done in two ways:

  1. Using a constructor

  2. Using a setter method

3. List out the number of ways to provide configuration to Spring Container.

XML-based, Annotation based, Java-based.

4. What is a DispatcherServlet?

It receives incoming requests from clients and dispatches those requests to the correct resource (handlers). These handlers are identified by @Controller.

5. What is a Spring Bean?

The objects of a class are called Beans in Spring. The objects which play a very crucial role in the spring framework and are managed by the Spring IOC can also be termed as Spring Beans.

6. Explain Singleton Scope for a Bean.

In Spring, when the scope is Singleton, only one object for that class is created. Singleton is the default scope.

7. What is the use of @RequestMapping?

This annotation is used to map a URL to

  • An entire class (or)

  • A controller method.

8. What is a Spring Security Context?

SecurityContext holds the information of the current user, provided the user is authenticated. In other terms, Spring Context can also be called a Principle. 

9. What is Authentication in Spring Security?

When a user is logged in with a username and password, the system or application can check if the password is correct or not. In the case of a correct password, a context/environment is set to the user.

10. Who is an Anonymous User in Spring Security?

Till the time a user gets Authentication, the user remains anonymous. These users will not be able to access any of the resources or URLs till they get authentication. Once they get authentication, they are granted roles (Admin, Manager, etc.)

11. What is OAuth Authentication?

Some applications allow the user to log in using their social network (Facebook, Gmail, etc.) log in credentials, such an Authentication is called OAuth Authentication.

Tips for the aspirants

  • Concentrate on the basics first before going to any of the advanced concepts of all Java technologies or frameworks.

  • Do a good practice of the concept explained and try the same in different ways.

  • Explore more about the concepts by reading articles available over the internet. 


In the year 2015, Java celebrated its 20th anniversary. Throughout this 20-year tenure, Java has developed drastically. Many technologies, versions (1.8), and/or frameworks were introduced by this leading programming language. Not only this, Java is now extensively used in mobile application development. It is a good decision if one has taken to make a career in Java, as it has become a promising path for newbies. 

Good Luck!


Full Stack Developer Course

About the Author

Meet Kiran Ramanadham, a talented writer who enjoys baking and taking pictures in addition to contributing insightful articles. He contributes a plethora of knowledge to our blog with years of experience and skill.

Join OdinSchool's React Web Development Course

With Job Assistance

View Course