Top 30 Java Interview Questions and Answers (2024)

Java Interview Questions for Experienced

Directives are instructions processed by the JSP engine. After the compilation of the JSP page into a Servlet, directives insert external files, set page-level instructions, and define customized tag libraries. We define directives using the following symbols:

start with "< %@" and then end with "% >" 

Different types of directives are:

  • Page directive: It defines particular attributes in the JSP page, such as buffer and error page.

  • Include directive: It comprises a file and combines the content of an entire file with the active pages.

  • Taglib: It declares a custom tag library used on the page. 

JCA stands for Java Cryptography Architecture. It provides architecture and application programming interfaces to enable decryption and encryption. Developers use JCA to combine an application with security applications. Moreover, it helps implement third-party security rules, for which it uses encryption message digest, hash table, etc.

Packages are the collection of related classes and interfaces bundled together. Developers can use packages to modularize the code and enhance its reusability easily. Classes can also import the code within packages and reuse it. Some of the advantages of packages are:

  • Easier access control on the code.

  • A proper hierarchical structure makes it easier to locate related classes.

  • It helps in avoiding name clashes.

  • It can have hidden classes that are not visible to outer classes and are used only within the package.

Object-oriented programming (OOPs) is a programming style associated with the following concepts:

  • Abstraction: It is the method of hiding the implementation details from users and allowing them to see only the functionality-related information.

  • Encapsulation: It refers to wrapping the data and code together as a single unit.

  • Inheritance: It is a process where one class inherits or acquires traits and attributes of another class.

  • Polymorphism: It is the ability of a variable, object, or function to take more than one form.

Here are the differences between aggregation and composition in Java:




The parent class shares a one-way relationship with the child class.

The parent class owns the child class.

The child class has its individual life cycle.

The child class doesn’t have a lifetime. 

Denoted by an empty diamond in Unified Modeling Language notation.

Denoted by a filled diamond in the UML notation

It is a weak relationship like a bike with an indicator.

It is a stronger relationship like a bike with an engine.

Here are the differences between Heap and Stack Memory:


Stack Memory

Heap Memory


It is used by one thread of execution.

It is used by every part of the application.

Memory Size

It is comparatively smaller.

It is larger in size. 


It is less flexible, so you can’t change the allocated memory.

You can change the allocated memory.


Objects in the stack memory can’t be accessed by other threads.

Objects in the heap memory have global accessibility.

Memory Management

Follows LIFO (Last In, First Out) order to free memory.

Based on dynamic memory allocation.


Here, variables are visible to only the owner thread. 

It allows visibility to all threads.


Exists until the end of the execution of the thread.

Exists from the start until the end of application execution.


Fast allocation, access, and deallocation. 

Slow allocation, access, and deallocation.


Contains local primitive and reference variables to objects.

When an object is created, it’s always stored in the Heap space.

Order of Allocation



We can divide Java design patterns into different types, namely Structural patterns, J2EE patterns, Behavioral patterns, and Creational patterns.

Structural Patterns

  • Adapter

  • Bridge

  • Filter

  • Composite

  • Decorator

  • Facade

  • Flyweight

  • Proxy

J2EE Patterns

  • MVC Pattern

  • Data Access Object pattern

  • Front controller pattern

  • Intercepting filter pattern

  • Transfer object pattern

Behavioral Patterns

  • Interpreter

  • Template method/ pattern

  • Chain of responsibility

  • Command pattern

  • Iterator pattern

  • Strategy pattern

  • Visitor pattern

Creational Patterns

  • Factory method/Template

  • Abstract Factory

  • Builder

  • Prototype

  • Singleton

In Java, Wrapper classes provide a mechanism to convert the primitive data types into the reference or object types and vice-versa. Each primitive data type has a class assigned to it known as a wrapper class, as it wraps the primitive type into an object of that class. Conversion primitive type into objects is called autoboxing, whereas converting an object into a primitive data type is known as unboxing. 

One of the main applications of a wrapper class is changing a value in a method. As Java doesn’t support the class by reference, any changes in a method will have no effect on the original value. So, we can change the original value by converting the types into objects. Moreover, a wrapper class lets us perform serialization by converting an object into a stream.

The final keyword in Java is a predefined term used while declaring values to variables. When we declare a value using the final keyword, the value of a variable remains constant throughout the execution of a program. This special keyword is used as a non-access modifier. We can use the final variable in different contexts, as explained below:

  • Final variable- When we use the final keyword with a variable, its value can’t be changed once it is assigned. If no value is assigned to the final variable, then a value can be assigned only by using the class constructor.

  • Final method- The final method can’t be overridden by the inheriting class.

  • Final class- Once a class is declared final, we can’t extend it by any subclass, but it can extend any other class. 

Polymorphism in Java is the ability of an object to be processed in multiple ways. It defines a feature of being able to assign different meanings or uses to a variable, object, or function in various contexts. It is used when the parent class refers to the child class reference. There are two types of polymorphism:

  • Compile-time Polymorphism: It is a method overloading with two or more methods having the same name with arguments and return type.

  • Run-time Polymorphism: It is done using interface and inheritance. Run-time polymorphism of the dynamic method dispatch allows users to resolve the overridden method at runtime instead of compile-time.

Intermediate Java Interview Questions

Classloader is a part of JRE and is used to dynamically load the .class files into the JVM. Whenever a Java file is executed, the classloader triggers. 

There are three types of classloaders, as explained below:

  • Extension Classloader: Also known as the parent of the system classloader and child of the bootstrap classloader, the extension classloader only loads the files available in the extension classpath, ‘ext.dirs/JRE/lib/ext directory. In case there is no file in this directory, it will delegate it to the system classloader.

  • Bootstrap Classloader: It is the superclass of extension classloader and loads the standard JDK files from rt.jar and other core classes. The rt.jar file comprises package classes of, java.util, java.lang,, java.sql, etc.

  • System/Application Classloader: It loads the classes of application type in the environment variable such as -classpath or -cp command-line option. Also, it generates a ClassNotFoundException when the class is not available in the application classpath.

Here is a comparison between Iterator and Enumerators in Java:



Iterator is an interface available in the java.util package.

Enumeration is an object generating one element at a time.

Uses three methods, namely hasNext(), next(), and remove().

Uses two methods, which are hasMoreElements() and nextElement().

Allows removing elements from the given collection at the time of the iteration with well-defined semantics.

It is used to pass through a collection, generally of unknown size.

Reflection in Java is a runtime API used for defining the inspection capability of a code on another one, either of itself or of the system, and changing it during the run time. It inspects and modifies the behavior of methods, interfaces, and classes. 

It is a powerful and beneficial tool that allows programmers to analyze interfaces, classes, methods, and fields during runtime without knowledge of what they are called at the compile time. Java reflection is also used to call methods, set field values, and create new objects. 

To use user-defined external classes, it’s important to create instances of objects with fully-qualified names. Debuggers can use reflection in Java to assess private members of classes. 

Let’s understand reflection better with the help of an example. There is an object of an unknown type, and a method ‘fooBar()’ is needed to call on the object. 

Java’s static typing system doesn’t allow invoking the method unless the object type is known. This is achieved by Java reflection, which allows the code to scan the object and determine if there is a method named ‘fooBar().’ If yes, it will call the method as needed.

In Java, equals() is defined in the object class and is used to check the equality of two objects that are defined by business logic.

On the other hand, ==, also known as the equality operator, is a binary operator used to compare primitives and objects. The object class provides public boolean equals(Object o) method. The default implementation uses == to compare two objects.

Aggregation in Java represents the relationship between two classes, which can be best described as a ‘Has-A’ and ‘whole/part’ relationship. This is a one-way relationship between two classes and a specialized version of an association relationship. Here, the aggregate class has the instance of the class it owns.

When a class is able to possess only one object at a time, it is known as a singleton class in Java. The following are the essential steps to implement a singleton class:

  • The class must have only one object.

  • The object must have global access.

Here is a brief explanation of the Java thread lifecycle:

  • New: When a thread is newly created and the start() method hasn’t been invoked, the thread is said to be alive and in the new state. 

  • Runnable: Once a thread is started or the start() method is invoked before the JVM calls the run() method, the thread is considered to be in the runnable state. Here, the thread executes the task. 

  • Running: Once the run() method is invoked and the thread starts execution of the task, the thread is in the running state. 

  • Blocked/ Waiting: When a thread is unable to run despite being alive, it is in a non-runnable state. Sometimes, a thread wants to enter the synchronized code but has to wait and stay idle because another thread is operating in that block on the same object. So, the thread waits until the other thread is finished, and once the signal to execute is received, it comes to the running state again. 

  • Termination: Termination means the thread is not active anymore. So, when the run() method execution is done, the thread enters the termination state, becoming inactive and can’t be revived. 

The main method in Java is static by default because it doesn’t require an object to call the static methods. Also, it allows the compiler to call it before or after creating a class object. 

The compiler begins the program execution in the main() function in every Java program. Hence, it must be called by the compiler. If the main method is allowed to be non-static, the JVM has to instantiate its class to call the method, which will require more memory allocation.

Java Interview Questions for Freshers

Java is a high-level programming language developed by James Gosling in 1982 while he was working for Sun Microsystems. This secure, fast, and reliable language is used to develop large-scale applications and games.

We can say that Java is a completely object-oriented programming language as everything in Java is within the class that can be accessed by creating objects. 

However, one can also claim that Java is not completely object-oriented as it has the support of primitive data types, such as float, double, int, char, boolean, etc. 

So, we can conclude that Java is not a pure object-oriented language as it has direct access to primitive data types, which directly don’t belong to the integer class.

Suggested Reading: OOPs Concepts in Java

Java is a popular and widely-used computer programming language independent of platforms. It doesn’t require you to rewrite the complete program for each platform as Java virtual machine and Java bytecode support platform independence. 

You can run the platform-neutral bytecode through JVM (Java Virtual Machine), which translates the bytecode into machine code. As Java can operate on various operating systems without having to rewrite code for every platform, it is also known as ‘Write Once, Run Anywhere’ (WORA).

Hence, Java is platform independent.

Here are the differences between Java and C++ programming:





As the Java compiler generates platform-independent byte code, it is compatible with all machines. In Java, programs are written once and run everywhere.

C++ is not platform-independent and is based on the principle of ‘write once, compile anywhere’.

Interaction with the Library.

The native libraries of Java do not provide direct call support. Users can use Java native interface or access the libraries.

Access to the native system libraries directly is possible in C++. Hence, making it a better option for programming at the system level.

Compiler and Interpreter

It is a compiled and interpreted language.

It is only a compiled language.

Language Compatibility

Most of the Java languages are incompatible and are comparable to those of C and C++.

C++ programming language is based on the C programming and many other high-level languages are compatible with C++.


It has an automatic garbage collection and doesn’t support destructors at the moment.

It has similar features to procedural and object-oriented languages. 

Multiple Inheritances

Java doesn’t support the concept of multiple inheritance. Due to avoiding the complexity of name ambiguity, there is a diamond problem. 

It supports multiple inheritances 

For beginners, pointers are quite complicated and unsafe to use. As Java focuses on code simplicity, pointers can make it challenging. Using pointers can also lead to potential errors. 

Moreover, it can compromise security as users can easily access memory through pointers. It can also make garbage collection slow and prone to errors. Therefore, Java has furnished a certain level of abstraction by not using pointers. It uses references instead that can’t be manipulated, unlike pointers.

The following are the key features of Java programming:

  • Simple Learning Curve: Java is easy to learn and understand, which makes it a popular language among beginners.

  • Platform-independent: Java is based on the principle of ‘write once, run anywhere,’ so it supports multiple platforms, including Linux, Windows, Mac, Sun Solaris, and more. 

  • Object-oriented: In Java, everything is considered an object. This means that class and methods have the behavior and state of an object.

  • Robust: It has strong memory management because there are no pointers. The automatic garbage collection feature prevents memory leaks.

  • Secure: Its secure feature allows the development of a virus-free and tamper-free system. 

  • Portable: It is easy to convert a Java program into Java bytecode, so it is easy to execute it on any platform.

  • Interpreted: The code converted into Java bytecode is interpreted and executed by the Java interpreter.

JIT, also known as the Just-in-Time compiler, is a crucial part of the Java Runtime Environment. It is used to enhance the performance of Java-based applications during run time. 

JIT compiles parts of byte code that have similar functionality, which reduces the compilation time required for the code to run. We can say that the Java compiler is a translator to convert source code into machine-executable code. 

Here’s how the compiler works:

  • The javac compiler converts the Java source code into byte code.

  • The JVM loads the .class files at runtime using an interpreter, which is converted to machine-understandable code.

  • JIT is a crucial part of Java Virtual Machine. Once JIT is enabled, the JVM assesses the method calls in the .class files and compiles them to make code more efficient and native. This also optimizes the prioritized method calls.

  • Last, the JVM executes the optimized code rather than interpreting it again. This improves the performance and speed of execution.

We get two key think with the Java download file- JDK (Java Development Kit) and 

JRE (Java Runtime Environment).


Java Development Kit

Java Runtime Environment

It is a dedicated kit used for solely software development.

It is a set of software and library created for executing Java programs.


It is also platform-dependent. 

JDK package is a set of tools that are used for debugging and developing.

JRE package supports files and libraries for a runtime environment.

JDK package is provided with an installer file.

JRE package does not have an installer but a runtime environment.

Java constructors are the block of code used to initialize an object. A constructor must have the same name as the class. Moreover, it has no return type and is called automatically when an object is created. 

There are two types of constructors:

  • Parameterized Constructor: Parameterized constructors accept the parameters so users can initialize the instance variables at the time of instantiating the class with the provided values. In short, we can say that constructors that take arguments are known as parameterized constructors.

  • Default Constructor: This type of constructor doesn’t accept any parameters or inputs but instantiates the class variables with their default values. Hence, it doesn’t take arguments created by default when the user defines no other constructor. It is primarily used for object creation.

Here are the differences between ArrayList and Vector in Java:



ArrayList is not synchronized, which makes it fast.

Vector is synchronized, which makes it slow.

If an element is inserted into an ArrayList, the Array size increases by 50%.

Vector defaults to doubling its array size.

It does not define the increment size.

It defines the increment size.

It can use only iterator for traversing.

It can use enumeration and iterator for traversing.

The super keyword in Java is a reference variable used to access hidden fields and overridden methods/attributes of the parent class. It refers to the immediate parent class object. When we create a subclass instance, we also create a parent class instance referenced by the super reference variable. 

The super keyword is used in the following cases:

  • To call the constructor of the immediate parent class within the child class.

  • Access data members of the parent class when the class and subclass have the same name.

  • To access methods of the parent class when the child class has overridden it.

Following are the main differences between JVM, JDK, and JRE in Java:






Java Development Kit

Java Runtime Environment

Java Virtual Machine


It is an extensive software development kit used for developing Java applications and includes JRE, JavaDoc, compiler, debuggers, etc.

It is a software package with Java class libraries, JVM and other components required to run Java applications.

It is a platform-dependent abstract machine with 3 specifications- a computer program meeting the JVM requirements, a document describing the JVM implementation requirements, and an instance object for executing the Java byte code and providing the runtime environment for execution.

Main Purpose

Mainly used for development and execution.

Key purpose is creating an environment to execute the code.

It provides specifications for all the implementations to JRE.


Offers tools, such as a compiler, debuggers, and more for code development.

Offers libraries and classes that JVM needs to run the program.

Does not include any tools but provides the specification related to implementation.


JDK = JRE + Development tools

JRE = JVM + Libraries to execute the application

JVM = Runtime environment to execute Java byte code.