Top 75 Java Interview Questions and Answers


Our NSCHOOL Academy lists out the most relevant Java Interview Questions and Answers that will help you stand outstanding throughout the technical interview process. Java is used by approximately 10 million developers worldwide to create applications for the 15 billion Java-enabled computers. It’s also used to bring cutting-edge technology like Big Data to everyday devices like mobile phones. As a result, Java is being used all over the world! This is why Java Certification is the most sought-after qualification in the programming field.

This technical blog will bring a clear understanding to all java beginners as well as for java professionals. Since, our blog holds the most approximate java interview questions for freshers and java interview questions for experienced too. Get ready to explore the Java world by viewing the Java interview questions 2021.

  1. What is Java?

Java is a platform-independent, high-performance, multithreaded, and portable high-level, object-oriented, robust, and stable programming language. It was founded in June 1991 by James Gosling. Since it comes with its own JRE and API, it’s also known as the web.

  1. Why is Java called Platform Independent and Architectural Neutral?

Java is a cross-platform programming language. It differs from other programming languages, such as C and C++, which need a framework to run. Java comes with its own framework, which is used to run its code. The execution of Java is not dependent on the operating system. So, we call it as Platform independent language.

Java is architecturally agnostic, meaning it isn’t influenced by the architecture. The size of data types in C will differ depending on the architecture (32 bit or 64 bit), but this is not the case in Java. So, it is called Architectural Neutral.

  1. What do you mean by JVM?

A virtual machine that allows a computer to run a Java programme is known as a Java Virtual Machine. The JVM functions as a run-time engine that calls the key method in Java code. The Java Virtual Machine (JVM) is a specification that must be implemented in a computer system. JVM compiles Java code into Bytecode, which is computer independent and similar to native code.

  1. What is JRE?

Java Runtime Environment (JRE) is an acronym for Java Runtime Environment. That is the JVM implementation. The Java Runtime Environment (JRE) is a set of software resources for creating Java applications. It’s responsible for creating the runtime environment. That is the JVM implementation. It exists physically. It includes a set of libraries as well as other files that JVM uses during execution.

  1. What is JDK?

The acronym JDK stands for Java Development Kit. It’s a software development environment for creating Java applets and applications. It also exists physically. JDK is an implementation of the Oracle Corporation’s Java Platforms, as described below:

  • Standard Edition Java Platform

  • Enterprise Edition Java Platform

  • Micro Edition Java Platform

  1. List the type of memory areas allocated by JVM?

Java allocates the variables used in the following kinds of memory areas.

  • Class

  • Heap

  • Stack

  • Program counter registration

  • Native method stack

  1. Explain Java stack?

Frames are stored in Java Stack. It handles local variables and partial results, as well as invoking and returning methods. Each thread has its own JVM stack, which is generated concurrently with the thread. Whenever a method is called , a new frame is generated. When a frame’s method invocation is over, it is killed.

  1. Explain JIT Compiler.

JIT (Just-In-Time) compiler: It is employed in order to enhance efficiency. JIT compiles portions of the bytecode with identical features at the same time, reducing the amount of time it takes to compile. The term “compiler” refers to a converter from a Java virtual machine’s (JVM) instruction set to the instruction set of a particular CPU.

  1. What makes Java ‘write once, run anywhere’ function possible?

The bytecode makes it possible. The Java compiler transforms Java programmes into class files (byte code), which are a language that sits between source code and machine code. This bytecode is platform dependent, meaning it can be run on any machine.

  1. What is Inner class and Subclass?

A class that is nested within another class is referred to as an inner class. An inner class has access to all variables and methods specified in the outer class, as well as the class it is nested.

A subclass is a class that derives from another class known as the super-class. A subclass has access to all of its superclass’s public and safe methods and fields.

  1. Explain the various Access specifiers in Java class?

Access specifiers are keywords that are used before a class name in Java to describe the access scope. The following are examples of class access specifiers:

1. Public: Class, Method, and Field are all public. That is they are meant to be accessed from anywhere.

2. Protected:Methods and fields can only be accessed from within the same class, from sub-classes, and from within the same set, but not from outside.

3. Default: Methods, fields, and classes can only be accessed from inside the same package, not from outside.

4. Private: Methods and fields that are private can only be accessed from the class to which they belong.

  1. What is the use of Static methods and Static variables?

We use the static keyword to render a method or a variable shared for all objects when we need to share a method or a variable between multiple objects of a class rather than making separate copies for each object.

  1. Explain Singleton class?

In Java, a singleton class can only have one instance, and all of its methods and variables belong to that instance. If there is a need to restrict the number of objects for a class, the singleton class definition comes in handy.

If there is a restriction on making only one access to a database due to driver restrictions or licencing problems, this is the best example of singleton use.

  1. Explain loops and list the types of loops.

In programming, looping is a technique for repeatedly executing a statement or a collection of statements. In Java, there are three types of loops:

  • for

  • while

  • do while

  1. Define Object in Java

The Object is a real-time entity that has a state and behavior. In Java, an object is a class instance with instance variables that represent the object’s state and methods that represent the object’s actions. The new keyword can be used to build a class object.

  1. What is an object oriented paradigm?

It’s a programming paradigm that revolves around objects that have data and methods specified in the class to which they belong. The modularity and reusability benefits of the object-oriented model are intended to be incorporated. Objects are instances of classes that communicate with one another to create programmes and applications. The object-oriented model has the following characteristics.

  • In terms of software design, it takes a bottom-up approach.

  • With methods to work on the object’s data, the emphasis is on data.

  • Encapsulation and abstraction are concepts that mask complexities from the user and only present features.

  • Implements real-time techniques such as inheritance, abstraction, and so on.

  • C++, Simula, Smalltalk, Python, C#, and other object-oriented programming languages are examples.

  1. What will the initial value of an instance variable identified as an object reference be?

In Java, all object references are set to null.

  1. Explain Constructor.

A Constructor is the specific type of method that initializes an object state. It is called when the object’s memory is allocated and the class is instantiated.The default constructor of the class is called, whenever an object is created using the new keyword. The class name should be similar to the name of the constructor. And a Constructor will not have an explicit return type.

  1. Explain the two types of constructors used in Java?

In Java, there are two types of constructors based on the parameters passed in the constructors.

Default constructors: Default Constructor does not accept any value. The default constructor is primarily used to set the default values for instance variables. It can also be used for some useful tasks related to object construction. A default constructor is called implicitly by the compiler if the class does not define any constructor.

Parameterized constructor: The Parameterized constructor is the one that can set the values for the instance variables. To put it another way, we can call parameterized constructors that can accept arguments.

  1. Do Constructor return any values?

Yes, The constructor will implicitly return the current instance of the class (explicit return type with the constructor cannot be used.)

  1. Explain Java methods.

A method is used to reveal an object’s actions. A return type is required for a method. The method is called directly. In any case, the compiler does not provide the method. The name of the method may or may not be the same as the name of the class.

  1. What is an Interface?

In Java, an interface is a reference type. It’s equal to a class. It consists of a collection of abstract methods. When a class implements an interface, it inherits the interface’s abstract methods.

An interface can also contain constants, default methods, static methods, and nested types in addition to abstract methods. Method bodies are only available for default and static methods.

  1. Is it possible to declare constructors inside the interface?

No, constructors are not permitted in interfaces. Interface variables are static final variables, which means they are constants, and we cannot construct objects for them.

As a result, there is no need for a constructor in an interface, which is why it is not possible to build one.

  1. What are the constraints that apply to Java static methods?

The static methods are subject to two major constraints.

  • The static method is unable to use non-static data members or explicitly call non-static methods.

  • Since this and super are non-static, they can’t be found in static contexts.

  1. Why do we use the main method static?

Since calling the static method is not expected of the object. If we render the main method non-static, the JVM would have to generate its object first and then call the main() method, resulting in additional memory use.

  1. What is a static block?

The static data member is initialised with a static block. At the time of classloading, it is executed before the key process.

class A2




System.out.println(“static block is invoked”);


public static void main(String args[])


System.out.println(“Hello main”);



Output: static block is invoked

Hello main

  1. Tell me about the Instance method.

The instance method is a method that is not declared as static. The instance methods must be named by the object.Instance methods can access both static and non-static variables.

Ex: public void msg(){…}

  1. Can you make constructors static?

The static context (method, block, or variable) belongs to the class, not the object, as we all know. It makes no sense to make constructors static since they are only called when the object is made. If you attempt to do so, the compiler will show a compiler error.

  1. What is Inheritance?

Inheritance is a process that allows one object to inherit all of the properties and behaviours of another object of the same class. It’s used for reusing code and overriding methods. Inheritance in Java refers to the ability to build new classes that are based on existing ones. When you inherit from an existing class, you can use the parent class’s methods and fields.

The 3 types of inheritance are listed below,

  • Single-level inheritance

  • Multi-level inheritance

  • Hierarchical Inheritance

Java does not allow multiple inheritance by classes.

  1. Why Inheritance is used in Java?

There are a number of benefits to using inheritance in Java, which are mentioned below.

  • Inheritance allows code to be reused. If it is appropriate to have a particular implementation of the method, the derived class does not need to redefine the method of the base class.

  • It is difficult to achieve runtime polymorphism without using inheritance.

  • Real-time artefacts can be used to model class inheritance, making OOPs more practical.

  • Inheritance allows data to be hidden. By keeping certain data private, the base class will keep it hidden from the derived class.

  • Without inheritance, method overriding is impossible. We can offer a particular implementation of some simple method contained by the base class by method overriding.

  1. Why does Java not support multiple inheritance?

Multiple inheritance is not allowed in Java to reduce complexity and simplify the language. Consider the following scenario: A, B, and C are 3 different classes. The A and B classes are inherited by the C class. If A and B classes have the same method and you call it from a child class object, the method of A or B would be unclear.

Since compile-time errors are superior to runtime errors, if you inherit two classes, Java produces a compile-time error. There will be a compile time error if you use the same approach or a different one.

  1. What are the different types of Inheritance in java?

There are 3 types of inheritance supported by Java:

Single Inheritance: In single inheritance, one class inherits the properties of another, meaning that there will only be one parent and one child class.

Multilevel Inheritance: Multilevel Inheritance is a type of inheritance in which a class is derived from another class that is also derived from another class, i.e. a class with multiple parent classes but at different levels.

Hierarchical Inheritance: When a class has several child classes (subclasses), or when more than one child class has the same parent class, this is referred to as hierarchical inheritance.

  1. Explain Method Overloading?

  • In Method Overloading, While methods of the same class have the same name, each method must have a different number of parameters, as well as different types and orders of parameters.

  • Method overloading is the process of “adding” or “expanding” the action of a method.

  • It’s a polymorphism that occurs at compile time.

  • The signatures of the methods must be different.

  • In Method Overloading, inheritance may or may not be needed.

Sample program for Method Overloading.

class Adder {

Static int add(int a, int b)


return a+b;


Static double add( double a, double b)


return a+b;


public static void main(String args[])





  1. Explain Method Overriding?

  • In Method Overriding, the subclass has the same method as the superclass, with the same name, number and type of parameters, and return type.

  • The aim of method overriding is to “Change” the method’s current actions.

  • It’s a polymorphism that occurs during the execution of a programme.

  • The signatures of the approaches must be identical.

  • Inheritance is often required in Method Overriding.

Sample program for Method Overriding is,

class Car {

void run() {

System.out.println(“car is running”);


Class Audi extends Car{

void run()


System.out.prinltn(“Audi is extremely stylish”);


public static void main( String args[])


Car b=new Audi();;



  1. Explain Encapsulation in Java?

Encapsulation is a technique for merging data (variables) and code (methods) into a single object. The data is hidden from the rest of the world and can only be accessed via the methods of the current class. This aids in the protection of data from unnecessary alteration. In Java, we can achieve encapsulation by:

  • Declaring a class’s variables as private.

  • To adjust and display the values of the variables, public setter and getter methods are given.

  1. Explain Association in Java?

The term “association” refers to a relationship in which each entity has its own lifecycle and there is no owner. Consider the relationship between a teacher and a student. Multiple students can be associated with a single teacher, and a single student can be associated with multiple teachers, but the objects do not share ownership, and each has its own lifecycle. One-to-one, one-to-many, many-to-one, and many-to-many partnerships are all possible.

  1. Tell me about Aggregation in Java?

An aggregation is a type of association in which each object has its own lifecycle, but there is ownership and a child object cannot be a parent object. Let’s also see the Department and the teacher as an example. A single teacher cannot belong to more than one department, but the department teacher object would not be destroyed if the department is deleted.

  1. Explain Composition in Java?

We may call this a “death” relationship since composition is a specialised type of Aggregation. It’s a powerful form of Aggregation. Child objects do not have a lifecycle, and if the parent object is removed, all child objects are deleted as well. Let’s look at a partnership between House and rooms once more. Multiple rooms can be found in a house. There is no separate life for a room, and no room may belong to two different houses; if the house is deleted, the room would be deleted as well.

  1. Explain Marker Interface.

A Marker interface is one that doesn’t have any data members or member features. The Marker interface, to put it another way, is an empty interface. Serializable, Cloneable, and other Marker interface examples in Java are the most common. The following is how the marker interface can be declared.

public interface Serializable{


  1. Explain Object cloning in Java?

The method of making an exact copy of an object in Java is known as object cloning. It generally means being able to construct an entity that is in the same state as the original. To accomplish this, Java provides the clone() process, which can be used to allow use of this feature.This method generates a new instance of the current object’s class and then populates all of its fields with the same values as the corresponding fields. The java.lang marker interface is used to clone an object. To prevent any runtime exceptions, Cloneable must be enforced. One thing to keep in mind is that Object clone() is a safe method that must be overridden.

  1. Explain the copy constructor in Java?

A member function called copy function Object() { [native code] } is used to initialise an object with another object of the same class. Since all objects in Java are transferred by reference, there is no need for a copy constructor. Furthermore, Java does not allow automatic pass-by-value pass-through.

  1. Explain constructor overloading in Java?

Constructor overloading is a Java technique that allows you to add any number of constructors to a class, each with its own parameter list. The compiler distinguishes overloaded constructors based on the number of parameters and their types in the list.

class Demo


int i;

public Demo(int a)




public Demo(int a,int b)





  1. Explain Java Servlets.

  • Java Servlet is a server-side technology that enables web servers to expand their functionality by allowing for dynamic responses and data persistence.

  • Interfaces and classes for writing our own servlets are provided by the javax.servlet and javax.servlet.http packages.

  • The javax.servlet interface must be implemented by all servlets. Servlet lifecycle methods are described by the Servlet interface. We can extend the GenericServlet class provided with the Java Servlet API when implementing a generic service. The HttpServlet class contains methods for managing HTTP-specific services, such as doGet() and doPost().

  • Web applications are usually accessed via the HTTP protocol, which is why we often expand the HttpServlet class.

  1. Explain the difference between get and post methods.



Since data is transmitted in headers, only a limited amount of data can be sent.

Since data is sent in the body, a large number of data can be sent.

Since data is exposed in the URL bar, it is not safe.

Data isn’t exposed in the URL bar, so it’s secure.

It’s possible to bookmark

It’s not possible to bookmark



It is more effective and widely used than Post

It is less effective and widely used than

  1. Explain Request dispatcher.

The RequestDispatcher interface is used to forward the request to another resource in the same programme, which may be HTML, JSP, or another servlet. This can also be used to add content from another resource to the answer.

The 2 methods defined in this interface are:

1.void forward()

2.void include()

  1. What do you know about Polymorphism?

Polymorphism is defined as “one interface, many implementations” in a nutshell. Polymorphism is the ability to assign a different meaning or usage to something in different ways – specifically, the ability to provide several forms for an entity such as a variable, a function, or an object. Polymorphism can be divided into two categories:

  1. Compile time polymorphism

  2. Runtime polymorphism

Method overloading is used in compile time polymorphism, while inheritance and interfaces are used in runtime polymorphism.

47. Do you know why Pointers are not used in Java?

Pointers are not used in Java because they are unsafe and add to the program’s complexity. Since Java is known for its code simplicity, introducing the idea of pointers would be incompatible. Furthermore, since the JVM is responsible for implicit memory allocation, pointers are discouraged in Java to prevent direct memory access by the user.

48. Explain break and continue statements.

Break: It can be used in switch and loop statements (for, while, do while). It terminates the switch or loop statements as soon as they are executed. It immediately ends the innermost enclosing loop or switch.

Continue: This function can only be used with loop statements. It does not end the loop, but instead allows it to leap to the next iteration. The next loop iteration will be triggered by a continue inside a loop nested with a turn.

49. Explain Abstraction in Java.

The quality of dealing with concepts rather than events is referred to as abstraction. It essentially entails covering the specifics and only displaying the most important information to the user. As a result, abstraction in Java can be described as the process of hiding implementation information from the user and only revealing functionality.

50. What position do Cookies play in Servlets?

Cookies are text files that a server sends to a client and saves on the client’s local computer. Through javax.servlet.http, the Servlet API supports cookies. Serializable and Cloneable interfaces are implemented by this cookie class.Since there is no point in adding a cookie to a request, the HttpServletRequest getCookies() method is given to get the list of cookies from the request. There are no methods to set or add a cookie to a request.

Similarly, the HttpServletResponse addCookie(Cookie c) method is used to add a cookie to the response header; however, there are no getter methods for cookies.

51. Explain the JDBC driver?

JDBC Driver is a piece of software that allows a Java programme to communicate with a database. JDBC drivers are divided into four categories:

Bridge driver for JDBC and ODBC

Driver for native APIs (partially java driver)

Driver for the Network Protocol (fully java driver)

Driver with a thin frame (fully java driver)

52. What does the JDBC DriverManager class do?

The registered drivers are regulated by the DriverManager class. It is possible to register and unregister drivers with it. It has a factory method that returns a Connection case.

53. What do you mean by JDBC Statements?

JDBC statements are statements that are used to send SQL commands to a database and retrieve data from it. JDBC includes a variety of methods for communicating with the database, including execute(), executeUpdate(), executeQuery(), and so on.

54. Tell me about Spring?

The Spring framework is “an application framework and inversion of control container for the Java platform,” according to Wikipedia. While any Java application can use the framework’s core features, there are extensions for developing web applications on top of the Java EE platform.”Spring is a lightweight, integrated platform for designing enterprise Java applications.

55. Explain Bean in Spring.

Beans are the objects that make up a Spring application’s backbone. The Spring IoC container is in charge of them. In other words, a bean is an entity that a Spring IoC container creates, assembles, and manages.

56. Tell me about Autowiring in Spring?

The programmer will inject the bean automatically using autowiring. We don’t need to write injection logic directly. Let’s take a look at the code for injecting a bean with dependency injection.

<bean id=“emp” class=“com.javatpoint.Employee” autowire=“byName” />

57. Tell us about Hibernate Framework?

The programming technique of object-relational mapping, or ORM, is used to map application domain model objects to relational database tables. Hibernate is a Java-based object-relational mapping (ORM) tool that allows you to map application domain objects to relational database tables and vice versa.

Hibernate provides a reference implementation of the Java Persistence API, making it an excellent ORM tool with loose coupling benefits. For CRUD operations, we may use the Hibernate persistence API. With the use of JPA annotations and XML-based configuration, the Hibernate framework can map plain old Java objects to standard database tables.Similarly, hibernate configurations are adaptable and can be done programmatically or through an XML configuration file.

58. Explain Hibernate Architecture.

Hibernate has a layered architecture that allows users to work without knowing the underlying APIs. The database and configuration data are used by Hibernate to provide persistence services (and persistent objects) to the application. Many objects are included, including persistent objects, session factories, transaction factories, link factories, session, and transaction factories.

There are four levels of Hibernate’s architecture.

  • Application layer in Java

  • Framework layer for Hibernate

  • Database layer

  • Database layer

59. Mention the different tags provided in JSTL.

There are five different forms of JSTL tags.

  1. core tags

  2. sql tags

  3. xml tags

  4. internationalization tags

  5. functions tags

60. Explain the jspDestroy method?

javax.servlet.jsp calls the jspDestroy() function. When a JSP page is about to be deleted, the JspPage gui is named. The kill methods of Servlets may easily be overridden to perform cleanup, such as when closing a database link.

61. What makes JSP superior to Servlet technology?

JSP is a server-side technology that makes content generation easy. Servlets are systems, although they are document-centric. A Java server page can contain Java programme fragments that run and instantiate Java classes. They do, however, appear inside an HTML template file. It serves as a foundation for the development of a Web application.

62. Explain in detail about Error and Exception.

An error is an unrecoverable condition that occurs during the execution of a programme. For example, an OutOfMemoryException. You can’t fix JVM errors in the middle of a game. Although an error can be caught in the capture block, the application’s execution will be halted and will not be recoverable.

Exceptions, on the other hand, are situations that arise as a result of bad input, human error, or other factors. For example, if the required file does not exist, a FileNotFoundException would be thrown. If you try to use a null reference, you’ll get a NullPointerException. In the vast majority of instances, an exception can be recovered from (most likely by providing the consumer with suggestions for entering proper values, etc.).

63. How will you handle Java Exceptions?

In Java, there are five keywords that are used to manage exceptions:

  1. try

  2. catch

  3. finally

  4. throw

  5. Throws

64. Explain Finally block?

Finally, a block that always executes a sequence of statements is known as a finally block. Regardless of whether or not an exception exists, it is often correlated with a try block.

If the programme exits by calling System.exit() or by making a fatal error that causes the operation to abort, eventually it will not run.

65. Tell me about OutOfMemoryError in Java?

OutOfMemoryError is a subclass of java.lang.Error that occurs when our Java Virtual Machine (JVM) runs out of memory.

66. Tell us about Thread.

A thread is the smallest unit of programmed instructions that a scheduler can execute independently. Any Java programme will have at least one thread, referred to as the main thread. When the JVM begins executing the programme, it creates this key thread. The main thread is used to call the program’s main() function.

67. How will you create a Thread?

Threads can be generated in Java in two different ways:-

  • Through making use of the Runnable interface.

  • By extending the Thread.

68. What is the work of Garbage collectors?

Garbage collection is a Java software that aids in the management of implicit memory. Since the new keyword in Java allows you to build dynamically generated objects, which will consume memory once they are created. When the job is finished and there are no more references to the object, Java uses garbage collection to delete it and free up the memory it has taken up.

69. Is it possible to write several catch blocks inside a single try block?

Yes, multiple catch blocks may be combined into a single try block, but the method should be general rather than unique. Let’s take a look at an example programmatically.

public class Example {

public static void main(String args[]) {

try {

int a[]= new int[10];

a[10]= 10/0;


catch(ArithmeticException e)


System.out.println(“Arithmetic exception in first catch block”);


catch(ArrayIndexOutOfBoundsException e)


System.out.println(“Array index out of bounds in second catch block”);


catch(Exception e)


System.out.println(“Any kind of exception in third catch block”);



70. Explain Synchronization in Java?

Multi-threading is referred to as synchronisation. Only one thread can execute a synchronised block of code at a time. Since Java allows multiple threads to run concurrently, two or more threads can access the same fields or objects. Synchronization is a mechanism that ensures that all concurrent threads are running at the same time. Synchronization prevents memory consistency errors caused by a faulty shared memory view. When a method is declared as synchronised, the monitor for the method’s object is held by the thread. If the synchronised method is being executed by another thread, the thread is blocked before that thread releases the monitor.

71. What is the checked exception?

Checked exceptions are all classes that extend Throwable except RuntimeException and Error. Exceptions that are checked are checked at compile time. IOException, SQLException, and other exceptions are examples.

72. What is an unchecked exception?

Unchecked exceptions are the classes that extend RuntimeException. At compile time, unchecked exceptions are not verified. ArithmeticException, NullPointerException, and other exceptions are examples.

73. How will you disable session in JSP?

By applying this command, you disable the JSP session <%@ page session=“false” %>

74. How will you integrate Spring and Hibernate frameworks?

If you’re using Hibernate 3+, where SessionFactory provides the current session, you can avoid using HibernateTemplate or HibernateDaoSupport classes and instead use the DAO pattern of dependency injection for the integration.

Additionally, Spring ORM supports Spring declarative transaction management, which you can use instead of using hibernate boilerplate code for transaction management.

75. Tell us about BatchProcessing in JDBC.

Instead of executing a single query, batch processing allows you to combine similar SQL statements into a batch and execute them all at once. You can execute several queries using JDBC’s batch processing technique, which speeds up performance.


Finally, the Java interview questions blog comes to a close. The skill sets that recruiters look for in a Java Professional are the ones that you heard about in this Java Interview Questions blog. These Java Interview Questions will undoubtedly assist you in acing your next work interview. To have a clear idea on Java current aspects and practical training mechanisms, visit our NSCHOOL Academy Java course page at Now, Best wishes for your Java Developer interview!