Top 100 Java Interview Questions and Answers

Java is one of the most common programming languages that is used in the software world. While sitting for your Java interview, make sure that you have a strong foundation. Core Java interview questions are often tricky. Therefore, we have a compilation of 100 core Java interview questions that you might face during your interview. Get ready to nail your answers to the Java interview questions in flying colors. 

Contents show

Things to keep in mind while you prepare for Java interview questions

  1. Make sure you have touched base with the basic concepts of programming
  2. Be honest with your answers to all the interview questions
  3. Acquaint yourself with practical application of programs
  4. Attend mock interviews with peers and friends
  5. While you answer your Java interview questions, try to explain with examples 
  6. Use diagrams to explain your answers more vividly
  7. Use this list of questions as part of your preparation

Interview Questions and Answers 

1) What is Java?

Java is a programming language used to write code for various kinds of applications. It uses class-based ideologies in its implementation. Also, Java is heavily dependent on object-oriented programming. Developers use it due to its unique “WORA” concept. Which means write once, run anywhere.

It is compatible across various platforms like Hibernate, Spring, etc. One of the reasons Java is used heavily in the developer’s world is its flexibility. Java applications are easy to set up and run. All you need is a JVM (Java virtual machine). There is no defined architectural requirement. 

2) Who found Java? What is the origin?

James Gosling from Sun Microsystems founded Java in 1995. In the year 1991 three employees were working on a Java programming language project. It was planned to create an interactive television Java program. It was supposed to be named ‘oak.’ During its course of development, it was known as ‘green’.

Eventually on its inception, ‘Java’ was the name used for this language. Java is over two decades old. It was a customized programming language for the company which had a wide range of implementations. It has its own compiler, virtual machines, etc. It was built on a set of libraries that allowed the usage of different in-built classes and functions. As the years progressed, a Java community kept growing its horizons. 

3) What is an object?

The most basic and fundamental component in Java is called an object. All elements that work towards making the Java program work can be referred to as an object. There are three things that one must understand when it comes to Java objects.

  1. State: The properties of a Java object are reflected by its properties.
  2. Behaviour: The usage of the object and its interaction with other objects within the Java class.
  3. Identity: Like human beings are referred to by a name. Even objects in Java are called by a name for identification. 

Java Interview Questions and answers 

4)  Define a Java Class.

Java Class: A place where objects are created as a prototype for the user. These objects have properties and functions that are used to execute a certain Java program. The class becomes common to all the residing variables and objects. This is the list of components in the class.

  1. Modifiers
  2. Class keyword
  3. Class name
  4. Superclass
  5. Interfaces
  6. Body

5)  How is an object created?

Java is essentially used to create a carbon copy of objects. Objects are derived out of a class. The keyword ‘NEW’ usually gets triggered to create new Java objects. Following are steps that need to be followed to create objects in Java. 

  1. Declaration – it refers to the mention of the variable and its type for the first time.
  2. Instantiation – this is where the new keyword will be used to call the object initially.
  3. Initialization – A call to a class constructor made to the new keyword. This process is used to initialize the object. 
Sample code 
public class Test_Puppy { //class test_puppy is created
   public cat(String name) {
      // one parameter, name.
      System.out.println("Name :" + name );// object is created
   Example public static void main (String []args) { //main method
      // this will create an object catname
      Test_Puppy catname= new cat( "tom" ); a class test_puppy variable is created
Name: TOM

 Java Interview Questions and Answers 

6) What is Object Oriented Programming?

The implementation of objects and writing the code with keeping objects in mind can be referred to as object-oriented programming in the Java programming language. It is a set of principles that are used during programming. The manner in which the data is used and how objects are used defines the principles of OOPs. The entire OOPs concept captures the following keywords. 

  1. Polymorphism
  2. Inheritance
  3. Encapsulation
  4. Abstraction
  5. Class
  6. Object
Object Oriented Programming

7) What are the main concepts of OOPs in Java?

  1. Abstraction: The main idea of abstraction is to make the application presentable. The user must not know exactly what’s behind the Java program at all times. It aims to give the most beautified output to the users. This is possible in Java with the help of its class based system. Here are the ways in which Java implements abstraction. 
    1. Hides complexity
    2. Blocks repetitive code
    3. There is a way to represent complex functionalities
    4. Programmer can control the behaviour through abstraction
    5. Partial and full abstraction (both) are possible. An abstract method is an example for the same
    6. Storing of local variables
  2. Encapsulation: The idea to protect certain data is implemented in Java using they protect and private abstract classes. It allows the programer to create a capsule of data. It groups and segregates data as per the usage. Here are the ways in which Java implements encapsulation
    1. Data is restricted within a class (public class is an exception)
    2. Parts of the code can be made private or protected (private method or protected method)
    3. Getter and setter class method can be used
    4. Usage of local variables in a method
  3. Polymorphism: the idea behind this concept is to have flexibility when it comes to functionality. The key to an oops programming language is that it allows the programmer to use a certain element in multiple ways without having to recreate it over and over again. Here are the ways in which Java implements polymorphism
    1. Objects in Java can be used multiple times
    2. Methods (either static method or non static method) in Java can be used as well
    3. Overloading of class method or method overloading
  4. Inheritance: The word basically means to receive a certain feature from the parent class (or base class) which can be a public class as well. The child-parent relationship can also be exercised in Java using this concept. There are classes in Java that enable the inheritance of classes. It can link classes and its attributes. Here parent class is the base class. The child class (or derived class) can also add its own features to the class and develop on it. Here are some ways in which Java uses inheritance.
    1. Child class (or derived class) from a parent class (in other words a base class is used to derive values to another class)
    2. Don’t repeat yourself (DRY) concept

8) Explain Abstraction in Java with an example

Classes are a key example for abstraction in Java. We can look at some sample codes that will help us explain abstraction.

Abstract class or abstract method in Java: This is the parent class or also known as superclass or base class. After the class creation, we need to add objects. Here is a sample class that captures the essence of abstraction by hiding the class objections from the main method or function of the program. In this case, it doesn’t matter if it is a public class or a private class. 

Sample code 
abstract class Test_Planet{
// abstract methods
abstract void water();
abstract void air();
// concrete method
void label() {
System.out.println("About planets");

Here we created the extension of planet class which have two planets – mars and earth (object is created)

Public class Test_Earth extends Planet{
void water() {
System.out.println("it has water");
void air() {
System.out.println("it has air");
Public class Test_Mars extends Planet{ // abstract methods
void water() {
System.out.println("no water");
void air() {
System.out.println("maybe air");

Now we can test these programs out by writing another public class. 

Public class TEST_EARTH{ // class test is created for earth 
public static void main(String[] args) { // main method
Planet  EARTH1 = new Earth(); // the class test has a variable
EARTH 1.label(); // object is created 
EARTH 1.water();
EARTH 1.air();
Public class TEST_MARS {
public static void main(String[] args) { // class test is created for another planet
Planet MARS2= new Mars();
MARS2.label();// abstract methods
MARS2.water();// sub class
About planets
It has water
It has air
No water
Maybe air

Java Interview Questions and Answers 

9) What is Java String Pool?

Strings are stored inside the Java heap. The storage area dedicated to strings is called the string pool. When one creates an object class like string a= “alphabet” the string is now stored inside a place in the Java virtual machine. It allocates part of the memory in the string pool. 

10) What is a classloader in Java?

The Java runtime environment gets loaded dynamically using the class loader in Java. The classes get processed into the Java virtual machine (JVM) using this class loader. All classes can not be made available in the JVM at once, therefore the class loader is evoked by JRE (Java runtime environment). 

Java interview questions - classloader in Java

11) What are constructors in Java?

A class constructor is a method or function in Java which helps in the declaration of objects for the first time. The moment the objects are created, the constructor is called. 

Following is an example of a constructor:- 

Sample Code (Java Program)
public class Main { // main method
  int y;  // Create a public class attribute. It is an instance variable 
  // Create a public class constructor 
  public Main() { // start main method  Class test()   
  y = 15;  // initial value for the public class attribute y
  public static void main(String[] args) { // public void is also possible here
    Main NewObj = new Main(); // Class Constructor
    System.out.println(NewObj.y); // Print the value of y

12) What do you mean by an interface in Java?

The implementation of abstraction can be explained using interfaces in Java. It is known as the abstract class. There is a need to implement the interface in order to use it. There is a keyword called ‘implements.’ Alternate keyword is ‘extends.’ Here is a sample code.

// interface
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void sleep(); // interface method (does not have a body)
// Dog "implements" the Animal interface
Public class Dog implements Animal {
  public void animalfood() {
    // The body of animalfood() 
    System.out.println("The dog food");
  public void class test() {
    // the body of test
    System.out.println("bhow bhow");
class TheMainClass {
  public static void main(String[] args) { // main method
    Pig newdog= new dog();  // Create a dog object
    newdog.animaltest();// created for class test
The dog food
bhow bhow

13) What is constructor chaining in Java?

When an object class is initialised and a sequence of constructors get declared, the constructor chaining is initiated. This usually happens when multiple constructors are called in a sequential manner. The two class methods used to form the constructor chaining are – this () and super (). This() is used for the calling class and super () is used for the inherited class method. 

14) What is the final keyword in Java?

When the programmer needs to restrict the user, the keyword final is used. It can be used in the following forms :- 

  1. Class
  2. Method 
  3. Variable

Final variables can be null as well. They need not be initialised. Within the constructor, the final variables can be called. The value of the variable can not be changed once a variable is called using the final keyword. 

15) Differentiate between the constructors and methods in Java?

Initialize an object (with the help of local variables)Methods create functionalities for the program
Implicit invocations (run method)Methods have explicit invocations
Default constructors (in case its not declared)No default methods in Java (run method)
Name of the default constructor has to match the name of the class object. Method name has to be different from the name of the class object.

16) Name the different modules of the Spring framework

Following are the modules in the spring framework. 

  • AOP
  • Spring IOC container
  • OXM module
  • Java Messaging Service
  • Transaction module
  • Servlet module
  • Application context module
  • DAO
  • Context
  • WEB MVC framework
  • ORM
  • JDBC  
different modules of the Spring framework

17) What is a Thread?

Any path that has to be followed by a program is referred to as a thread. The JVM creates one thread (which is known as the main thread). This formed at the starting of the program. 

Any process in the program is defined by a thread. There is a list of tasks that get queued. Based on the availability of threads the task gets initiated. The pool of thread determines the pace at which tasks can be executed. The threads in Java are managed by – Java.lang.thread class object. 

The diagram below depicts how threading works. As you can see there is a queue of tasks. There is a thread pool, which allows six connections (specific to the diagram). Every time a task is completed by the thread, the next task in the queue is allocated to that particular thread. One completion of the task, the thread gets free. 


Core Java Interview Questions and Answers 

18) What are the differences between processes and threads?

Any active piece of code which gets executedIt is a backend program that manages the process.
They need to have heavy context switchingNot so heavy on context switching
Can be time consumingUsually optimal based on the number of threads
Memory sharing does not happenMemory sharing is possible
Processes take a lot of time while communicating with other processesIt is relatively faster. 
Resource requirements are moreResource requirements are minimal
Blockage of one part of the process does not lead to complete haltIf a single thread gets blocked the other threads also get halted
More time taken to end a processLess time taken to end the threading activity
More time to start the processMore time taken to start the threading activity

19) What is the difference between .equals () and == in Java?

.equals() – it is a method, it is used for content comparison

== – it is an operator, it is used to check the value of the component or final variable.

20) What are some of the important Spring annotations which you have used?

Here is the list of annotations that are used in spring.

  1. @Required
  2. @Autowired
  3. @Qualifier
  4. JSR-250 annotations

21) What are the differences between ServletContext vs ServletConfig?

Servlet Config – It is created by the servlet container. It gets invoked during initialization. It is an object that has parameters. All the servlet information is stored in this config file, which would be more or less in an XML format. 

Servlet Context – There are some objects that need to be shared with the entire application, which is when the servlet context objects are needed. 

Quick summary of differences:-

Servlet ConfigServlet Context
SpecificFor the entire application
<int-param> in <servlet><context-param> in <web-app>
Has an object of its ownThe object of this are used by the entire application

22) What is the exception hierarchy in Java?

exception hierarchy in Java

Throwable class object – It is derived from the previous node as shown in the diagram. It sits on the top of the exception hierarchy of Java. All exceptions belong to the throwable class object. It is available inside the Java.lang.package.

Error class object – This comes under the throwable class object. Any issue occurs in the JVM, the program is terminated. These errors come during the runtime. Following are the errors that we can see commonly in Java. 

  1. VirtualMachineError
  2. StackOverflowError
  3. AssertionError
  4. LinkageError
  5. OutofMemoryError

Exception class object- These are the errors caused due to some external factors that are beyond the scope of the program. 

  1. Public exception ()
  2. Public exception (string)

Further, we can look at the exceptions in the diagram below. 


23) What are the different types of inheritance in Java?

Here are the different types of inheritance in Java:- 

Single inheritance  – this is where objects of once class are inherited from another class object. It is like a single parent – child relation.

types of inheritance in Java

Multiple Inheritance – The class 1 is the base class here and class 2 is the derived class. it is when a single class is inherited by two child classes (it is a derived class)

Multiple Inheritance

Multilevel Inheritance – Here class 1 is the base class. The rest of the two classes are the child class or sub class. When a class is derived from an inherited class, it is known as multi-level inheritance. 

Multilevel Inheritance

Hierarchical Inheritance – when a single parent has more than 2 child classes.

Hierarchical Inheritance

Hybrid inheritance  – When there is a combination of multiple and single inheritance, it is called hybrid inheritance. 

Hybrid Inheritance

24) What are the differences between default constructor injection and setter injection?

Key FeaturesConstructor InjectionSetter Injection
OrderingAn order needs to be followed for dependency injection. Uses a default constructor based DIBased on the requirements, the setter injection is performed for the dependencies.
CircularCan’t allow this injectionCan’t allow this injection
Multi Thread EnvironmentMore safety in this environmentThere is no added layer of security here
Spring Code generationLibrary does not support it. Library is supported here
Use CasesMandatoryOptional

25)  Explain Bean in Spring and List the different Scopes of Spring bean.

Objects that are managed by the spring IoC containers are referred to as beans in the spring framework. It is part of the spring bean factory. Following are the functions that are performed with bean scopes:-

  • Instantiation  (method for starting the bean)
  • Assembly  (a method)
  • Management of Spring  container (using a method)

The beans are used to configure the metadata in the spring container. Below is a list of bean scopes in the spring framework. There is a method for each one of these parts. 

  1. Class
    1. Class object
    2. Class method
  2. Name
  3. Scope
  4. Constructor-arg
  5. Properties
  6. Autowiring mode
  7. Initialization method
  8. Destruction method
  9. Lazy-initialization mode

26) Difference between method Overloading and method Overriding.

Method OverridingMethod Overloading
Method overriding is for enhancing the readability of the programMethod overloading is similar to repeating the main contents of a super class object. 
Method overriding occurs inside the classMethod overloading happens with two connected classes
The parameter used have to be different in method overridingSame parameters are used here in method overloading
Method overriding is basically a display of polymorphism (one of the OOPs concepts)  – compile timeMethod overload is basically a display of polymorphism (one of the OOPs concepts)  – run time
Return type can be anythingReturn type must be the same as the super class object. 

Example of overloading method and overriding method

class Overloading{  //method starts
static int add(int x,int y){return x+y;}  
static int add(int x,int y,int z){return x+y+z;}  
class Books{  
void read(){System.out.println("Pages...");}  // method
class Shakespeare extends Books{  
void read(){System.out.println("Pages and Word Count....");}  // method

27) List the features of Java Programming language.

  1. It is simple
  2. OOP based language 
    1. Object – variable, method
    2. Class
    3. Inheritance
    4. Polymorphism
    5. Abstraction (usage of abstract class is an example)
    6. Encapsulation
  3. Robust
  4. Platform Independent
  5. Secure
  6. Multi threading
  7. Neutral architecture
  8. Portable
  9. High performance
  10. Distributed

28) What are the JDBC API components?

The JDBC API is part of the overall architecture of the program. Where it sits right below the Calling Java application followed by the JDBC driver manager. Network connections are also established at this stage. Post which the middle ware is wired through the application server (where the code is written) and then connected to the database.  The classes for spring JDBC API have four different components.

  1. Core 
  2. Object
  3. Support
  4. Datasource
JDBC API components

Java Interview Questions and Answers

29) Explain the role of DispatcherServlet and ContextLoaderListener.

Here is a table that talks about both the dispatcher servlet and context loader listener with respect to the various features of Java. 

FeaturesDispatcher ServletContext Loader Listener
BeansControllers are usedServices and DAO are used
OptionalNo. Spring applications always require the dispatcher servletYes. Spring applications can survive without context loader listeners. 
ContainerCreates its own application contextIt is defined in the web.xml
Basic Request is sent to the spring mvc controllerReads the configuration text then parses it further

30) Name the types of transaction management that Spring supports.

There are different ways to handle the programmatic transaction management in Spring. Following are some types of transaction management staples. Note that some can be declarative transaction management related terms. 

  1. Programmatic: use the code to help you manage the whole system. There is high flexibility. However, it can be challenging to maintain. 
  2. Declarative: The business code remains separate from management. This will help you maintain the two separate portions with ease (with xml template). However, there is a lack of flexibility in this case.  XML based code can be written here.  The files are stored in a xml based configuration file. Also this is part of the declarative transaction management feature of spring.

31) What is Multiple Inheritance? Is it supported by Java?

Multiple Inheritance – One of the key features of Java, is when a single class object is inherited by two child classes. The method of class 1 moves to class 2. 

Multiple Inheritance

Following is the example of multiple inheritance in Java. Here there are two classes. Once in the class that allocates the salary of the employee in the company. The child class (or derived class) works with the salary of a particular designation of the employee. The first class (Employee_comp) is the parent to the child class also known as a derived class. (Analyst). 

class Employee_Comp{  
 float salary=50000;  
}  // current class
class Analyst extends Employee_Comp{  
 int bonus=20000;  //instance variable
 public static void main(String args[]){  //main method
   Analyst a=new Analyst();   
   System.out.println("Analyst salary :"+a.salary);  
   System.out.println("Bonus of Analyst:"+a.bonus);  //current class instance
Analyst salary: 50000
Bonus of Analyst: 20000

32) How many types of memory areas are allocated by JVM?

JVMS are virtual machines that get allocated when necessary. It is a basic program in Java that works on converting byte code into machine code. It skims through the lines of code one after the other. It works as a translator for the machine. It works in real-time for a Java program. It gets called from the starting of the main() block. Below are the list of operations that are performed by a JVM.

  1. Give a runtime environment for the programmer 
  2. Loading of the code written 
  3. Execution of the written code
  4. Verification of the written code

Java Interview Questions

33) What is the difference between JDK, JRE, and JVM?

JDK stands for Java development kit. It is the software where the development tools are available for the programmer. It provides functions and libraries. There are various editions and platforms for a JDK. Here are the examples of a few:-

  1. Enterprise Edition
  2. Standard edition
  3. Micro Edition

JRE stands for Java runtime environment. It is the space for the entire application building. It contains libraries and files that are crucial during the compilation of the code. 

JVM is the virtual machine of the Java program that takes care of the memory and other essential components for the functioning of the code. It works as a translator between the program and the machine. 

Java virtual machine

Core Java Interview Questions 

34) Explain Hibernate architecture.

The architecture of the hibernate framework has four different layers –

  1. Application (Java) Layer- this contains the application servers
  2. Hibernate framework Layer
  3. APIs (application program interface) Layer – the apis are hosted here work on connection to the layers above and below this layer.
  4. Database Layer

The below diagram depicts the overall hibernate architecture for the Java program. Different components are highlighted in the box. 

hibernate architecture for the Java program

35) What are the differences between include directive and include action?

The table below draws a comparison between include directive and include action. 

Include directiveInclude action
The code is stored in a JSP file. It gets copied from one file to another in a static manner. The copying of one file to another happens dynamically.
Single servlet Multiple servlets
Can be jsp type file onlyCan be jsp, servlet or html
Tags – html and xmlOnly xml tags are used here
Syntax: <%@inlcude file= “    ” %>Usage in the static void main string (args)Syntax: <%JSP:include page= “  ”%>Usage in the static void main string (args)
File has to reside within the applicationFile has to reside anywhere on the server. 

36) What is the difference between an object-oriented programming (OOP) language and object-based programming language ?


  1. All of the following concepts are implemented
    1. Object
    2. Class
    3. Inheritance
    4. Encapsulation
    5. Abstraction
  2. It is used across many programming languages such as Java, c++, C#
  3. It has inbuilt method or function and objects

Object Based Programming

  1. Only object and encapsulation are part of the concepts
  2. Does not support – inheritance or polymorphism
  3. It does not have any inbuilt objects
  4. Visual basic or JavaScript are examples of object based programming languages. 

37) Can you override a private or static method in Java?

No, we can not override a private or static method in Java. Private methods in Java are built to be hidden within the private class (the one which it is first declared). The scope of the final variable in a private class are restricted to that particular class. Therefore a private method becomes inaccessible outside its score. 

Here is a block of code that can explain the concept better:

class Test{
   private void privatefunction() {
      System.out.println("Main class");    //main method - (can be used inside  to be mentioned in static void main string (args)) 
public class Trial extends Test{// current class object
   void privateFunction() // trying to override private function() or method {
      System.out.println("Sub class");
   public static void main (String[] args) {  // public static void main block begins
      Test a= new Trial();
      A.private function(); // method overriding 
Output (for the object): 
error: privateFunction() has private access in Parent

Java Interview Questions 

38) What is the difference between an Array list and vector in Java?

Array listVector
When it comes to synchronization, arrays are not synchronousWhen it comes to synchronization, vectors are synchronous.
The size is flexible. Even if additional elements are added, there is room to fit some extra bytes. The space for an increase in size is 50%The size is flexible. Even if additional elements are added, there is room to fit some extra bytes. The space for increase in size is 100%
Not from the legacy class objectIt is from a legacy class object
It is fastRelatively slow
In order to scan through each element, it uses an iterator interface.The traversal is possible via two methods – iterator interface and enumerator interface. 

39) What are the important methods of Java Exception Class?

  • Void printstacktrace()
  • Public Synchronised throwable getcause()
  • Public String tostring()
  • Public String getLocaliseMessage()
  • Public String getMessage()
  • Public throwable fillinStacktrace()
  • public StackTraceElement [] getStackTrace()

40) What are the different methods of session management in servlets?

Usually session management is dependent on the user’s requirements. A session id is used to keep track of the functions and programs within a web application. The following ways are in which session management is achieved in servlets. 

  1. Cookies
  2. URL rewriting 
  3. Hidden form fields 
  4. HTTPS and SSL

Java Interview Questions

41) How to create a custom Exception?

A custom exception is what the user creates using his or her own logic for the exception. Following is an example of the same. Check out the block of code below. 

class InvalidAge extends Exception{  
 InvalidAge(String a){  
class TestCustom{  // current class object
   static void validate(int age)throws InvalidAge{  // to be mentioned in public static void main string (args)  later
     if(age<18)  // instance variables 
      throw new InvalidAge("can not vote");  
      System.out.println("welcome to vote");  // to be mentioned in public static void main string (args)
   public static void main (String args[]){  // main method  - the beginning of the public static void main block
      }catch(Exception x){System.out.println("Exception occured: "+x);}  //(can be used inside  to be mentioned in public static void main string (args)) 
}  // end of the public static void main block
Exception occurred: InvalidAge: can not vote

42) What is the life-cycle of a servlet?

There are three parts of the life cycle – 

  1. init() – this is where the initial loading and instantiation takes place
  2. Service() – the objects of the code are initialised which get further pushed into handling of the requests received. 
  3. destroy() – once the functions are completed the servlet stops.
life-cycle of a servlet

43) What is the difference between abstract classes and interfaces?

The table below draws a comparison between the abstract classes and interfaces.

Abstract classInterface
These comprise of both abstract and non-abstract functions or methodsJava until now could only handle abstract class. 
There can not be multiple inheritance with Java abstract class object. There are multiple inheritances in interfaces, unlike an abstract class object. 
The following items are available in a Java class  object (abstract class) – static, non-static variables and final variable, non-final variablesStatic and final variables are the only ones accessible in an interface level. (no final variable here)
Implementation is possible hereImplementation is not possible here
Abstract – it is a keyword (while declaring an abstract class the keyword has to be used)Similarly, interface is also a keyword
It has the capability of using multiple interfaces within the same Java classAn interface and its functions are confined within its own scope.

Sample code

  1. Abstract Class
public abstract class Salary{ // example public class object
public abstract void BasicPay(); // example public class method also this can be called in the public static void main string (args) block
} // next comes the main thread
  1. Interface
public interface Deduction{ // example public class
Public void ProvidentFund();// instance of the class

44)What are wrapper classes in Java?

The purpose of wrapper class is to enable the usage of primitive classes in Java as an object.Here is the list for the wrapper classes in Java:-

  1. Character
  2. Boolean
  3. Double
  4. Float
  5. Long
  6. Integer
  7. Short
  8. Byte

45)Why is Java not 100% Object-oriented?

It may sound surprising but it is important to note that Java is not a hundred percent object oriented. It has the flexibility of supporting the primitive data types as well. The static keyword in Java is also not based on the OOPs concept. The wrapper class sets Java apart from the organic and pure OOP languages. 

Java Interview Questions

46) What purpose do the keywords final, finally, and finalize fulfill? 

Sometimes there are cases when restrictions have to be imposed on classes (main method or variables). Using the ‘final’ keyword will prevent any case of method overriding.Finally is basically a block. This would help the compiler identify the important parts of the code. It basically highlights those parts of the method.Finalize is not a keyword. It is a main method. It is used as part of the garbage collection in the garbage collector.  When there is a clean up required at the method level.. 

Java Interview Questions

47) . What are the differences between forward() method and sendRedirect() methods?

Forward()Send Redirect()
This is planted at the server-side of the applicationThis is on the client-side of the application
There are no new requests or responses created. It works with the same onesEverytime a new request is generated.
This only resides at the server levelThis is used across the application
Request. getRequest Dispatcher(“servletNEW”). forward(request,response); (can be used inside  to be mentioned in public static void main string (args)) Response. sendRedirect (“servletNEW”);(can be used inside  to be mentioned in public  static void main string (args)) 

48) What is a Map in Java?

A map has the value and the object. Each value-key pair is treated as a single entry. Map is known to generate unique keys with unique values. Java code is flooded with variables and objects and methods. Map helps in navigation of the specific key that one is looking for. 

Map in Java

Java Interview Questions

49) What is the difference between an array and an array list?

The table below discusses the differences between an array and an array list:-

ArrayArray List
It is like a small box in a memory that stores a value or a series of values. It is created dynamically. This is a class in Java. It has  – hash table, has maps, and vector
These have a fixed length as per the declarationThey vary in length 
The size of the array is declared at the beginning of declaration at the instance of the class. There are no such restriction on the size of the array list
In order to store a value in the array or change it or modify it. A loop has to be triggered (for loop)Instead of loops an iterator is used in case of the array list.
It is fast due to its relatively smaller sizeIt is heavy on the memory and can impact the performance of the program
Objects and primitive typesPrimitive types
Length of the variable is the length of the arrayNeed to use the size() function to determine its size
It is multidimensionalIt is single dimensional.

Java Interview Questions

50) Why are Java String objects immutable in nature?

The basic structure of Java strings consist of something called the string pool. There is caching activity that keeps happening. This leads to multiple sharing of the string objects across different clients. Which makes Java string objects highly immutable in nature. Also this makes them safe as the thread doesn’t need to be accessed by another set of threads explicitly. It is important to mark the thread safe in the Java runnable interface. 

51) Why is Java platform independent?

We all know that Java can be used across various frameworks. It is compatible for both web based applications and APIs. This is due to the way Java is structured and used. The byte code can run on various kinds of operating systems. The execution of its Java byte code program makes it platform independent. We can look at how the Java byte code program works. 

  1. The Javac compiles the code after it is written
  2. The byte code is the result of the compiler
  3. An interpreter like a JVM helps in translation of this byte code
  4. The jvm is compatible with all operating systems as well. 

52) What is Request Dispatcher?

In a servlet, the objects can carry the requests to the server. The interface that enables this is called the dispatcher. ‘Javax.servlet.RequestDispatcher’ helps in the forward movement of the response. Following are some methods that are part of the request dispatcher.

  1. forward()
Request Dispatcher - Forwarder
  1. include()
Request Dispatcher - Include

53) What are the differences between Checked Exception and Unchecked Exception?

Checked ExceptionUnchecked Exception
File not found
No such method
No such field
Class not found (inner class)
No such element
Undeclared throwable
Empty stack
Array index out of bounds
Null pointer
SecurityThese occur during the compilation of code also known as compile timeThese occur during the runtime of the code post compilationCompiler checks happen at this point and cause different kinds of checked exceptions (if any in the inner class)A compiler is not built to handle unchecked exceptions automatically. Since the exceptions are always an outcome of certain flaws in the program (logical errors at the inner class level).
There is something called the exception class in Java. Checked exceptions are part of this class. This is not part of any class.
The responsibility of catching the exception is on the JVM.JVM need not do so in this case

54) Differentiate between static methods and non static methods in Java.

The table draws a comparison between static methods and non static methods. 

Static MethodNon Static Method
Accessibility is limited to static members of the class. These methods or functions can access both static and non-static variables of the class
Compile time-binding and early binding is possible with static methodsNon static method is used since it is dynamic binding
Possibilities of overriding are not there in static methodsSince it is dynamic, it can be overridden. This method is used in various cases. 
Static methods take up less amount of spaceThese are heavy on the memory. Unlike the static variables, the memory allocation also occurs dynamically.
Static keyword is used to declare ( for example –  to be mentioned in public  static void main string (args))Nothing is required


public class Trial { // this class is the overall group
   public static void main (String args[]) { // main method - public static void main string (args)
     Dog dog = new Dog(); // inside public static void main string (args) 
     dog.drink(); // instance variables used here
} // runnable interface 
class Dog{ // dog is the name of the class in Java which captures the functionalities of dog
   public void drink(){
      System.out.println("Dog is drinking water"); // calling static method. Here the return type is string
   public static void eats(){ // instance variables used here
      System.out.println(“Dog is eating food"); // calling non static method. Here the return type is string
} //  end of public static void main string (args)
Dog is drinking water
Dog is eating food

55) What is the difference between this() and super() in Java?

This()Super ()
This is a keywordThis is a keyword
Helps in marking the current instance for a classThis is used to mark the current instance for a super class
A default constructor is called inside the classA default constructor is called in the super class
Can reference the class and also manage the functions within the class (it has a default constructor). This has access to all the methods and variables in the parent class (or base class)
Static Non static

56) What is an infinite loop in Java? Give an example.

A loop is used to create iterations. Usually, in order to traverse through an array, a loop is used to go through each element. In some cases the repetition can lead to a never-ending loop, leading to an error. This incident occurs due to something called the infinite loop.  Following is an example where the loop is unable to find an ending condition.

public void InfiniteLoopSample( int i )
   while ( i != 0 )
      i-- ;

57) What is the difference between break and continue statements?

Termination of the loop with the condition is trueContinuation of the loop in case the condition is true
This allows ending the loop and continue the rest of the codeIt limits the stay within the loop
It works with switch and labelIt can not be used with switch and label
Break Statement
Continue Statement

Java Interview Questions

58) Differentiate between the class constructors and methods in Java? 

Class ConstructorClass Method
Creation and initialization of objectsExecution of statements
Invoked due to usage of the keywordInvoked when the method calls are made through statements. 
No return typeReturn type exists
Name is the class name itselfIt can have any name except class name or a keyword
No InheritanceInheritance exists

Java Interview Questions

59) Explain public static void main(String args[]) in Java.

This is the basic syntax that must be followed through the program in Java. The public keyword is known as the access modifier. It states the access level of the class or function/method. Static defines the nature of the function or method. Void run can basically indicate the absence of data type.

This is to indicate the behavior or the method during runtime. A void run is a return type that basically means that the function or method can either return null or any desired value. The main portion points to the actual logical sequence of statements in the program.

The compiler always starts by looking at the code inside the main function or method. String args[] represents the fact that Java accepts arguments in the form of an array. Here the data type is strings. 

60) What is the difference between a local variable and an instance variable?

A local variable is declared inside a particular class and used within the class depending on the score. Whereas the instance variable can be declared anywhere, even outside the class. 

61) What is a constructor overloading in Java ?

Constructor overloading happens when same named constructors are created or called multiple times. It applies for a default constructor as well. The same method has different elements or parameters. 

62) What are the different types of garbage collectors in Java?

Memory management in applications is important. Applications are constantly running processes and engaging in a wide range of data flow. The control of memory by a certain process can be done by allocation of space. This is possible using a GC also known as the garbage collector. There are four different types of garbage collectors in Java –

  1. Serial Garbage Collector
  2. Parallel Garbage Collector
  3. Concurrent Mark Sween Garbage collector
  4. Garbage first (G1) Garbage collector

Questions on  garbage collectors are frequently asked Java interview questions .

63) What is a Serial Garbage Collector?

In this type of GC the garbage collection happens in a serial environment. Threads are used for the collection. When a process is running, threads are created. A Serial garbage collector is usually used in simple programs where there are only a few events happening at once point. 

Serial Garbage Collector

64) What is a Parallel Garbage Collector?

This is the kind of garbage collection that is used by most programs. It is the default mode by most of the JVMs. The working of the garbage collection is the same, it uses threads for processing the collection. However, multiple threads are engaged in the garbage collection event. Many heavy-weight applications need active garbage collection. The processing of garbage collectors can be enhanced by using multiple CPUs (central processing units). 

Parallel Garbage Collector

65) How does a garbage collector (GC) work?

Java has a way to manage memory using garbage collectors. Whichever objects remain idle and not get actively used get swept away by the garbage collector. One of the algorithms used by garbage collectors in Java is mark and sweep. Things to note down about garbage collectors

  1. Garbage collector is a thread
  2. There are methods which control the usage of GC – system.gc() and runtime.gc()
  3. JVM controls the garbage collector
  4. When the memory is full, there is an error thrown – Java.lang.OutOfMemoryError

66) What are access modifiers in Java?

The following are the two types of modifiers in Java:-

  1. Access modifiers
  2. Non Access modifiers

We will discuss the four types of access modifiers that are used in Java

  1. Private – this restricts the access of the variables and functions within the class. A function or method can also be declared as private, restricting the use of the given method. 
  2. Default – when there are no modifiers specified, the default mode is carried out. Even the default constructors are created within a method. 
  3. Protected – this restricts the access of variables and functions within a package. A protected method has values that are specific to the class. 
  4. Public – the method does not have any restrictions. The elements belonging to a public class are free to be used anywhere in the program. A public method can be used multiple times without any restrictions. 

67) What do you mean by Aggregation?

One way relationships in Java are denoted by the term called aggregation. For example a salary class can have a reference of address. However, the address can not have a reference of salary. It is also called a “Has-A” relationship. 

Class Address{
int street_no;
String city;
String state;
int pin;
Address(int street, String city, String state, int pin ){
this.street_no = street_no; = city;
this.state = state; = pin;
class Salary
  String basicpay;
  Address address;

68) What is the JIT compiler in Java?

For any program to run, a compiler is the most important unit of the development. The just in time (JIT) compiler in Java is part of the OpenJ9  VM that helps in performance of the Java program. There are different levels of optimizations –

  1. Cold – this is at the start of the process
  2. Warm – this is at the highest peak of the performance

69) What are the two ways of creating threads in Java?

The following are the two ways of creating threads in Java – 

  1. Extends thread class 
public class NEWThread extends Thread{
     public void run()
      System.out.println("Thread started..");
     public static void main( String args[] )
        NEWThread var= new  NEWThread();
        var.start(); // instance variables 
  1. Implement runnable interface
public void run() {
        System.out.println("Thread started ");
    public static void main(String args[]) {
        NEWThread mt = new NEWThread();
        Thread new_threadvar = new Thread(x);
        new_threadvar.start(); // object is created

Java Interview Questions

70) What is OutOfMemoryError in Java?

This error is thrown at the time of garbage collection. When there is not enough space left for further allocation of objects, there is a runtime error that is thrown called the OutOfMemoryError. This would call for the increase of the overall heap memory of the Java machine.

71) What is composition in Java?

In order to make the has-a relationship work, a design ‘composition’ is required in Java. A code is written to showcase the inheritance and significance of the has-a relationship between the objects like variables, methods etc. 

72) Why are pointers not used in Java?

Following are the reasons why Java does not support pointers unlike other programming languages like – C++ or C.

  1. Memory which gets utilized using a pointer can be detrimental to the Java program. The virtual machine model of Java can lead to complications when pointer memories are accessed.
  2. Security is compromised when pointers are used in an unstructured Java architecture. 
  3. The use of referencing or passing values by references.
  4. Pointers utilize memory that needs to be allocated explicitly which is not possible in Java memory management. As memory management in Java is done via JVM. This makes usage of pointers almost impossible in the Java programming language. 

73) What is numeric promotion in Java? Mention the types

Implicit casting is known as numeric promotion in Java. The idea is to promote the data type of a variable from one kind to another. For example:-

Int i = 3;

Double num = 34.2;

 Double sum = num + i ; // here the i is directly promoted to a double so that the numeric calculation is performed between two double types. The answer will be in double. 

The following are the two types of conversions – 

  1. Narrowing primitive conversion
  2. Widening primitive conversion

74) What is an association in Java?

Association in Java

When objects in different classes get linked together to perform some action, it is called association. The associations can be of many types as mentioned below:-

  1. One to one relationship
  2. Many to one relationship
  3. Many to many relationship

Also association is divided into two parts:-

  1. Aggregation 
  2. Composition

75) What is a try block (catch block) in Java?

There are chances that you can predict when an exception is being thrown. A try block (or a catch block) will help you block this from happening. The try block (or catch block) has to be used inside a method or a function. The catch block will be called up when the exception has to be enclosed. Another rule to keep in mind while using the try block (or catch block) is to make sure that the final block comes right after it. 


//code that may throw an exception    // catch block 
}catch(Exception_class_Name ref){}    
//code that may throw an exception    
Exception Handling in Java

76) What is synchronization in Java?

In Java resource sharing is common among variables, arrays and processes. Synchronisation allows this to happen by controlling access of multiple threads. Here is why you need to use synchronisation.

  1. Prevent thread interface
  2. Prevent any problems in consistency 

Following are types of synchronizations.

  1. Process synchronisation
  2. Thread synchronization

Further we can divide this into :-

  1. Mutually exclusive
    1. Method
    2. Block
    3. Static
  2. Corporative

77) What do you understand by JDBC Statements?

The interface that performs the database properties are called the jdbc statements. There are three types of statements which have their own unique functionality. 

  1. Statement – It is used to directly access the tables in the table of your database. Any static sql query can be noted as a statement. It could be calling a set of variables or the entire table. 
  2. Prepared Statement – This is called multiple times based on the functionality within the application. It is like a function or method that has to take some variables in order to run the statement.
  3. Callable statement – The stored procedures (these get triggered based on the functionalities pre-defined by the database administrator) can be accessed using the callable statements in the JDBC. 

78) What are the types of statement objects in Java?

  1. Boolean execute – a boolean value like – true or false is returned
  2. Int execute update – no. of rows that are affected can be indicated.
  3. Result set execute query  – usage of the ‘select’ statement occurs here. 

79) Name the three types of prepared statements in Java

  1. IN  – values are not known prior to running the statement
  2. OUT – it is the values that the sql statement retrieves 
  3. IN OUT – it provides both the input and output elements from the table. 

80) Differentiate between Javascript and Java

OOP based programming languageA lightweight programming language, not necessarily object-oriented language. It is an object-based programming language. 
Virtual environment is requiredNo virtual environment is needed
There are many rules and syntax for usage of methods, class etc. There are not any definite set of  fixed rules 
There is more memory consumptionIt is a lightweight program hence it is easy on the memory for most of the time. 
The extension file is .Java The extension file here is .js
A JVM is required to run the codeNo JVM or similar identity is required to run a Javascript program 

81) Can you have virtual functions in Java?

Although Java runs on a virtual machine, it is not possible for Java to have virtual methods or functions. A static function or method is not virtual as it is tied to a particular class and will not be able to exhibit polymorphism. 

82) What is the difference between JSE, JEE and JME.

difference between JSE, JEE and JME
  1. JSE is the Java standard edition. Following are some of the packages belonging to Java standard edition
    1. Java.lang
    2. Java.util
    4. Java.math
    5. Java.nio
    8. Java.sql
    9. Java.awt
    10. Java.time
    11. Java.beans
  2. JEE – it is the Java enterprise edition. It has APIs like – 
    1. Servlets
    2. Web Sockets
    3. Java server faces
    4. Unified expression language
  3. JME – it is Java micro edition which helps in mobile application development. 

83) What are the JSTL Tags in Java

JSTL stands for Java Server page standard tag library. It has a bunch of tags that help in identifying a particular library as in when required. Here is a list of tags that are available. 

  1. Core tags
  2. Formatting tags
  3. SQL tags
  4. XML tags
  5. JSTL Functions

84) What are the advantages of Hibernate over JDBC?

  1. Hibernate can be used with various databases like – Oracle, mySQL etc.
  2. There are no prerequisites required to use hibernate. Whereas while using JDBC, a certain level of understanding in SQL is required. 
  3. Hibernate performs automatic query tuning in the back-end 
  4. It works well with caching and storing such data when compared to JDBC. 
  5. No explicit mapping is required by the developer in case of hibernate
  6. Caching activity is automatic. JDBC requires a separate caching mechanism to be set up. 

85) Can we execute a program without the main () method?

One might rush to come to a conclusion on this. Every Java program has a main block. Therefore, it is often assumed that a main() block is a must. However, Java programs can be run on a static block as well. With the help of a class loader, static blocks are called and executed. 

86) What are the restrictions that are applied to the Java static methods?

There are certain restrictions placed on Java static methods. Here are few in the list:-

  1. Non static member or data can not be used
  2. This and super methods are not used here
  3. Access is restricted to static data only
  4. Object creation is not required to initialize the static method
  5. Overriding is eliminated in this case

87) Which package in Java has a lightweight component?

Except for the following packages, all components in Java are designed to be lightweight

  1. J Applet
  2. J Dialog
  3. J Frame
  4. J Window

88) State the difference between Swing and AWT components

Local windows toolkit like Java.awtNot applicable
No plugins for look & feelHas plugins for look & feel
Does not have model view controllerIt has a model view controller
Less number of componentsMore number of components

89) Demonstrate the hierarchy of Java swing. 

Java swing is part of the JFC which is known as the Java foundation class. It is primarily for creation of web based applications. Java swing is constructed on top of an abstract method called windowing toolkit. Java swing is not platform dependent. The picture below depicts the hierarchy of the Java swing.

hierarchy of Java swing

90) What is a stub in Java?

An object that is used at the client side of the web based application. It is used to identify and spot the Java class objects at the client side. The tasks performed by a stub are as follows:-

  1. Connect with virtual machine
  2. Import variables in the the virtual machine
  3. Result collection
  4. Reading of results and values
  5. Sending the information to the caller

91) Why Java doesn’t support multiple inheritance?

Multiple inheritance in Java can lead to ambiguity. This can lead to locking of memory space and objects in the JVM. 

92) When is the array store exception thrown?

The source destination of an array has to have the same data type and name while performing the copy function or method for arrays. If there is a mismatch discovered by the compiler then an exception is thrown. This exception is called – array store exception. 

93) What is an Applet in Java?

A web browser uses an applet to keep it running. Applet is like a small program that keeps websites alive. However, there are some distinct differences between an applet program in Java versus an actual Java program.

  1. Applet program has an extension with the name – Java.applet.Applet
  2. The applet program stands outside the main () block
  3. It is used with the HTML page
  4. Viewing of an applet based page leads to loading of a page 
  5. Like regular Java program, a virtual machine is required to use the applet based program

94) What is the Life cycle of a Java applet program?

  1. Initialise – Function or method to set up the program
  2. Start – Function or method  to begin the program
  3. Stop  – Once process is over, a function or method is required to end the program
  4. Destroy – To eliminate the unnecessary usage
  5. Paint – loads the page content

95) What is the role of JDBC Driver Manager class in Java?

The middleware that connects the user and drivers is called the JDBC driver manager class. There methods that help in driver management for jdbc. 

  1. Public static Void register driver() – method to register 
  2. Public static Void de-register driver() – method to drop when event ends
  3. Public static Connection getConnection() – method for URLs
  4. Public static connection getConnection() – method for passwords

96) What are the JSP implicit objects in Java?

JSP is a Java server page. Following are the list of implicit objects in JSP for Java. 

  1. Request – http servlet request
  2. Response – http servlet response
  3. Out – print writer
  4. Session – http session
  5. Application – servlet context
  6. Configuration – servlet config
  7. Page context – JSP writers
  8. Exception

97) What are the advantages of Java Server Page (JSP)?

  1. Dynamic elements improve the performance 
  2. Compilation is done well in advance
  3. The functions and methods can be called explicitly or implicitly 
  4. These are built over apis which makes them more easy to access. 
  5. They are built to support the business code more efficiently

98) Can we write multiple catch blocks under a single try block? 

Yes, it is possible to write multiple catch blocks underneath a single try block. The example below demonstrates the same. 

public class MultipleCatchBlockUnderTry {  
      public static void main(String[] args) {  
                int num[]=new int[5];    
               catch(ArithmeticException x)  
                   System.out.println("catch 1");  
               catch(ArrayIndexOutOfBoundsException x)  
                   System.out.println("catch 2");  
               catch(Exception x)  
                   System.out.println("catch 3");  

99) Why is vector class used in Java?

In order to use an array of objects that keep changing and growing, we need some functionality to manage such situations. Vector class gives the flexibility to use data that keeps modifying. There is no need to specify the size of the array in case of a vector in advance. This kind of dynamic flexibility helps the programmer use complex business logics for their programs. 

100) Are there any limitations in using inheritance in Java?

Inheritance occurs when objects from one class get copied to another. They are not linked together for the rest of the program. It can cause a lot of chaos and clustering. Which could lead to overriding and change of original values. Therefore, one has to use the access modifiers in Java to prevent this from happening in Java.  


Java is a complex programming language that has transformed over the years. There have been many changes made with the passage of time. These changes will continue to happen in the upcoming versions of Java. However, the basic fundamentals have remained intact from the beginning of its inception.

This compilation of Java interview questions can help you understand the concepts and revisit some basic functionalities. Also, these Java interview questions cover a wide range of topics that are part of Java programming. Make sure you use this list and revise it to give your best at your Java interview. 

Recommended Articles