Top 100 Java Developer Interview Questions and Answers
Jun 16, 2026 18 Min Read 6850 Views
(Last Updated)
Quick Answer: This guide covers 100 Java developer interview questions across beginner, intermediate, advanced, and scenario-based levels. It helps you revise Java fundamentals, OOP, collections, multithreading, JVM concepts, Spring Boot use cases, and backend problem-solving with clear answers.
Java was released by Sun Microsystems in 1995, but even after three decades, it still powers some of the world’s most important backend systems, enterprise applications, Android apps, banking platforms, and cloud-based products.
That is exactly why Java interviews are rarely limited to basic syntax. Recruiters want to know whether you can think like a real Java developer. They test your understanding of OOP, collections, exception handling, multithreading, memory management, JVM internals, Spring Boot scenarios, and production-level problem-solving.
This guide brings together beginner, intermediate, advanced, and scenario-based Java developer interview questions and answers in one place. Each answer is written in a clear, technical, and interview-ready format so you can revise faster, explain concepts better, and walk into your next Java interview with more confidence.
Table of contents
- Beginner-Level Java Developer Interview Questions and Answers
- What is Java?
- Why is Java Platform-Independent?
- What is the Difference Between JDK, JRE, and JVM?
- What Are the Main Features of Java?
- What is Bytecode in Java?
- What is the Difference Between Java and C++?
- What is the Role of the main() Method in Java?
- Why is Java Called a Strongly Typed Language?
- What Are Variables in Java?
- What Are Primitive Data Types in Java?
- What is the Difference Between == and .equals() in Java?
- What is Type Casting in Java?
- What is the Difference Between Implicit and Explicit Type Casting?
- What Are Java Operators?
- What is the Difference Between break and continue?
- What is a Constructor in Java?
- What is Constructor Overloading?
- What is the Difference Between a Constructor and a Method?
- What is the this Keyword in Java?
- What is the static Keyword in Java?
- What Are the Four Pillars of Object-Oriented Programming?
- What is Encapsulation in Java?
- What is Inheritance in Java?
- What is Polymorphism in Java?
- What is Abstraction in Java?
- What is the Difference Between Abstraction and Encapsulation?
- What is Method Overloading?
- What is Method Overriding?
- What is the Difference Between Overloading and Overriding?
- What is Dynamic Method Dispatch in Java?
- Intermediate-Level Java Developer Interview Questions and Answers
- What is the Java Collection Framework?
- What is the Difference Between List, Set, and Map in Java?
- What is the Difference Between ArrayList and LinkedList?
- What is the Difference Between HashMap and Hashtable?
- How Does HashMap Work Internally in Java?
- What is the Difference Between Comparable and Comparator?
- What is an Iterator in Java?
- What is the Difference Between Iterator and ListIterator?
- What is a Fail-Fast Iterator in Java?
- What is a Fail-Safe Iterator in Java?
- What is Exception Handling in Java?
- What is the Difference Between Checked and Unchecked Exceptions?
- What is the Difference Between throw and throws?
- What is the Purpose of the finally Block?
- What is a Custom Exception in Java?
- What is the Difference Between Exception and Error?
- What is Multithreading in Java?
- What is the Difference Between Process and Thread?
- What is the Thread Lifecycle in Java?
- What is Synchronization in Java?
- What is the Difference Between wait() and sleep() in Java?
- What is Deadlock in Java?
- How Can Deadlock Be Prevented in Java?
- What is the Difference Between Runnable and Callable?
- What is ExecutorService in Java?
- What is Garbage Collection in Java?
- What is the Difference Between Stack and Heap Memory in Java?
- What is the final Keyword in Java?
- What is the Difference Between final, finally, and finalize?
- What is String Immutability in Java?
- Advanced-Level Java Developer Interview Questions and Answers
- What is the Java Memory Model?
- What is the volatile Keyword in Java?
- What is the Difference Between synchronized and ReentrantLock?
- What is ThreadLocal in Java?
- What is CompletableFuture in Java?
- What is the Fork/Join Framework in Java?
- What is Reflection in Java?
- What are Java Annotations?
- What is a Custom Annotation in Java?
- What is Serialization in Java?
- What is serialVersionUID in Java?
- What is a ClassLoader in Java?
- What is the Difference Between ClassNotFoundException and NoClassDefFoundError?
- What is JIT Compilation in Java?
- What is Escape Analysis in Java?
- What is Metaspace in Java?
- What is the Difference Between Shallow Copy and Deep Copy?
- What are Generics in Java?
- What is Type Erasure in Java?
- What is a Bounded Type Parameter in Java?
- What is PECS in Java Generics?
- What is a Spliterator in Java?
- What is a Method Handle in Java?
- What is the Difference Between Reflection and MethodHandle?
- What are Records in Java?
- What are Sealed Classes in Java?
- What is Pattern Matching in Java?
- What is the Java Module System?
- What is the Foreign Function and Memory API in Java?
- What are Virtual Threads in Java?
- Scenario-Based Java Developer Interview Questions and Answers
- A Spring Boot API is taking too long to respond. How would you debug it?
- A user clicks the payment button twice. How would you prevent duplicate payment processing?
- A database query works fine in testing but becomes slow in production. What would you check?
- Your Spring Boot service is returning too much data in one API response. What would you do?
- A Java application frequently runs out of database connections. How would you solve it?
- A REST API sometimes saves partial data when an error occurs. How would you fix it?
- A Java service depends on another service that often fails. How would you protect your application?
- A login API is working, but users can access protected APIs without proper validation. What would you check?
- Your application logs are full of errors, but they do not explain the actual issue. What would you improve?
- A frequently used API is putting heavy load on the database. How would you optimize it?
- Java Interview Tips
- Conclusion
Beginner-Level Java Developer Interview Questions and Answers
1. What is Java?
Java is a high-level, object-oriented programming language used to build web applications, mobile apps, enterprise software, backend systems, and cloud-based applications.
Java is popular because it is secure, platform-independent, scalable, and widely used in backend development.
2. Why is Java Platform-Independent?
Java is platform-independent because Java code is first compiled into bytecode. This bytecode can run on any system that has a Java Virtual Machine.
This means a Java program written on Windows can also run on Linux or macOS without changing the source code.
3. What is the Difference Between JDK, JRE, and JVM?
JDK stands for Java Development Kit. It is used by developers to write, compile, and run Java programs.
JRE stands for Java Runtime Environment. It provides the required environment to run Java applications.
JVM stands for Java Virtual Machine. It executes Java bytecode and converts it into machine-level instructions.
4. What Are the Main Features of Java?
The main features of Java are object-oriented programming, platform independence, security, robustness, multithreading, portability, and automatic memory management.
These features make Java suitable for large-scale business applications and backend development.
5. What is Bytecode in Java?
Bytecode is the intermediate code generated after Java source code is compiled.
The Java compiler converts .java files into .class files. These .class files contain bytecode, which is executed by the JVM.
6. What is the Difference Between Java and C++?
| Java | C++ |
| Runs on JVM | Compiles to machine code |
| Platform-independent | Platform-dependent |
| Automatic garbage collection | Manual memory management |
| No direct pointer access | Supports pointers |
| No multiple inheritance with classes | Supports multiple inheritance |
| Used for web, Android, backend apps | Used for systems, games, embedded apps |
7. What is the Role of the main() Method in Java?
The main() method is the starting point of a Java program.
The JVM starts program execution from this method. A common Java main method is written as:
public static void main(String[] args)
8. Why is Java Called a Strongly Typed Language?
Java is called a strongly typed language because every variable must have a defined data type.
A variable declared as an integer cannot directly store a string value. This reduces programming errors and improves code reliability.
9. What Are Variables in Java?
Variables are containers used to store data in a Java program.
Each variable has a name, data type, and value. Example:
int age = 25;
String name = "Rahul";
Here, age stores a number, and name stores text.
10. What Are Primitive Data Types in Java?
Primitive data types are the basic data types provided by Java.
The eight primitive data types in Java are:
byte, short, int, long, float, double, char, and boolean.
They are used to store simple values such as numbers, characters, and true or false values.
11. What is the Difference Between == and .equals() in Java?
== checks whether two references point to the same memory location.
.equals() checks whether two objects have the same value, depending on how the method is defined.
Example:
String a = new String("Java");
String b = new String("Java");
Here, a == b is false because both objects have different memory locations. However, a.equals(b) is true because both values are the same.
12. What is Type Casting in Java?
Type casting means converting one data type into another data type.
Java supports two types of casting:
Implicit casting happens automatically when a smaller data type is converted into a larger data type.
Explicit casting is done manually when a larger data type is converted into a smaller data type.
13. What is the Difference Between Implicit and Explicit Type Casting?
Implicit type casting is automatic and safe. Example:
int num = 10;
double value = num;
Explicit type casting needs manual conversion. Example:
double value = 10.5;
int num = (int) value;
Explicit casting can lead to data loss because decimal values may be removed.
14. What Are Java Operators?
Java operators are symbols used to perform operations on variables and values.
Common Java operators include arithmetic operators, relational operators, logical operators, assignment operators, and increment or decrement operators.
Example:
int sum = 10 + 5;
Here, + is an arithmetic operator.
Prepare for Java developer interviews with confidence through HCL GUVI’s Java for Beginners Course. Build a strong foundation in Java programming, object-oriented concepts, exception handling, collections, and core development skills through structured lessons and hands-on practice designed for aspiring software developers.
15. What is the Difference Between break and continue?
break is used to stop a loop completely.
continue is used to skip the current loop iteration and move to the next one.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i);
}
This skips printing 3 but continues the loop.
16. What is a Constructor in Java?
A constructor is a special method used to initialize an object.
It has the same name as the class and does not have a return type.
Example:
class Student {
Student() {
System.out.println("Student object created");
}
}
The constructor runs automatically when an object is created.
17. What is Constructor Overloading?
Constructor overloading means creating more than one constructor in the same class with different parameters.
It helps create objects in different ways.
Example:
class Student {
Student() {
System.out.println("Default constructor");
}
Student(String name) {
System.out.println(name);
}
}
18. What is the Difference Between a Constructor and a Method?
A constructor is used to initialize an object. A method is used to perform an action or return a result.
A constructor has the same name as the class and does not have a return type. A method can have any valid name and may return a value.
19. What is the this Keyword in Java?
The this keyword refers to the current object of a class.
It is commonly used when instance variables and local variables have the same name.
Example:
class Student {
String name;
Student(String name) {
this.name = name;
}
}
Here, this.name refers to the instance variable.
20. What is the static Keyword in Java?
The static keyword is used for members that belong to the class rather than a specific object.
Static variables and methods can be accessed without creating an object of the class.
Example:
class Test {
static int count = 0;
}
21. What Are the Four Pillars of Object-Oriented Programming?
The four pillars of object-oriented programming are encapsulation, inheritance, polymorphism, and abstraction.
These concepts help developers write reusable, secure, modular, and maintainable Java code.
22. What is Encapsulation in Java?
Encapsulation means wrapping data and methods together inside a class.
It is usually achieved by keeping variables private and accessing them through public getter and setter methods.
Example:
class Employee {
private int salary;
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
23. What is Inheritance in Java?
Inheritance in Java allows one class to use the properties and methods of another class.
The class that inherits is called the child class. The class being inherited from is called the parent class.
Example:
class Animal {
void eat() {
System.out.println("Eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking");
}
}
24. What is Polymorphism in Java?
Polymorphism means one action can behave in different ways.
In Java, polymorphism is mainly achieved through method overloading and method overriding.
Example of method overloading:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
25. What is Abstraction in Java?
Abstraction means showing only important details and hiding internal implementation.
In Java, abstraction can be achieved using abstract classes and interfaces.
Example:
abstract class Vehicle {
abstract void start();
}
Here, the start() method is declared, but its internal logic is provided by child classes.
26. What is the Difference Between Abstraction and Encapsulation?
| Abstraction | Encapsulation |
| Hides implementation details | Hides internal data |
| Focuses on what an object does | Focuses on how data is protected |
| Achieved using abstract classes and interfaces | Achieved using private variables and getter/setter methods |
| Reduces code complexity | Improves data security |
| Example: Vehicle.start() | Example: private salary field |
27. What is Method Overloading?
Method overloading means having multiple methods with the same name but different parameters in the same class.
It improves code readability and supports compile-time polymorphism.
Example:
class MathOperation {
int sum(int a, int b) {
return a + b;
}
int sum(int a, int b, int c) {
return a + b + c;
}
}
28. What is Method Overriding?
Method overriding happens when a child class provides its own version of a method already defined in the parent class.
It supports runtime polymorphism.
Example:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
29. What is the Difference Between Overloading and Overriding?
Overloading happens in the same class. It uses the same method name with different parameters.
Overriding happens between a parent class and a child class. The child class changes the behavior of a parent class method.
Overloading is compile-time polymorphism. Overriding is runtime polymorphism.
30. What is Dynamic Method Dispatch in Java?
Dynamic method dispatch is the process where the method call is resolved at runtime.
It happens when a parent class reference points to a child class object.
Example:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
Animal obj = new Dog();
obj.sound();
Here, obj.sound() calls the Dog class method at runtime. This is dynamic method dispatch.
Intermediate-Level Java Developer Interview Questions and Answers
31. What is the Java Collection Framework?
The Java Collection Framework is a set of classes and interfaces used to store, manage, and process groups of objects.
It includes commonly used structures such as ArrayList, LinkedList, HashSet, TreeSet, HashMap, and Queue. Java developers use collections to handle data more efficiently in backend applications.
32. What is the Difference Between List, Set, and Map in Java?
| List | Set | Map |
| Stores ordered elements | Stores unique elements | Stores key-value pairs |
| Allows duplicates | Does not allow duplicates | Keys must be unique |
| Accessed by index | No index-based access | Accessed by key |
| Example: ArrayList | Example: HashSet | Example: HashMap |
33. What is the Difference Between ArrayList and LinkedList?
| ArrayList | LinkedList |
| Uses dynamic array internally | Uses doubly linked list internally |
| Faster for searching | Faster for frequent insertion/deletion |
| Better for read-heavy tasks | Better for update-heavy tasks |
| Access by index is faster | Access by index is slower |
34. What is the Difference Between HashMap and Hashtable?
| HashMap | Hashtable |
| Not synchronized | Synchronized |
| Faster in single-threaded use | Slower due to synchronization |
| Allows one null key | Does not allow null key |
| Modern and commonly used | Legacy class |
35. How Does HashMap Work Internally in Java?
HashMap stores data in key-value pairs. It uses the key’s hashCode() to decide where the entry should be stored.
Each storage location is called a bucket. Java compares keys using .equals() when two keys have the same hash bucket. This process helps HashMap retrieve values quickly.
36. What is the Difference Between Comparable and Comparator?
| Comparable | Comparator |
| Defines natural sorting | Defines custom sorting |
| Uses compareTo() method | Uses compare() method |
| Implemented inside the class | Created outside the class |
| Example: sort by name by default | Example: sort by salary or age |
37. What is an Iterator in Java?
An Iterator is used to traverse elements in a collection one by one.
It provides methods like hasNext(), next(), and remove(). Java developers use iterators when they need safe and controlled access to collection elements.
38. What is the Difference Between Iterator and ListIterator?
| Iterator | ListIterator |
| Works with many collections | Works only with List |
| Moves forward only | Moves forward and backward |
| Can remove elements | Can add, remove, and update elements |
| Simple traversal | More flexible traversal |
39. What is a Fail-Fast Iterator in Java?
A fail-fast iterator throws ConcurrentModificationException when a collection is modified while being iterated.
It helps detect unsafe changes during iteration. Common examples include iterators of ArrayList, HashMap, and HashSet.
40. What is a Fail-Safe Iterator in Java?
A fail-safe iterator works on a copy of the collection instead of the original collection.
It does not throw ConcurrentModificationException during iteration. Examples include iterators from CopyOnWriteArrayList and ConcurrentHashMap.
41. What is Exception Handling in Java?
Exception handling in Java is a mechanism used to handle runtime errors without stopping the program suddenly.
It uses try, catch, finally, throw, and throws. Good exception handling makes Java applications more stable and user-friendly.
42. What is the Difference Between Checked and Unchecked Exceptions?
| Checked Exception | Unchecked Exception |
| Checked at compile time | Checked at runtime |
| Must be handled or declared | Handling is optional |
| Example: IOException | Example: NullPointerException |
| Usually external issues | Usually programming mistakes |
43. What is the Difference Between throw and throws?
| throw | throws |
| Used to throw an exception manually | Used to declare possible exceptions |
| Written inside a method | Written in method signature |
| Throws one exception object | Can declare multiple exceptions |
| Example: throw new Exception() | Example: throws IOException |
44. What is the Purpose of the finally Block?
The finally block contains code that should run after try and catch.
It is commonly used to close files, database connections, network connections, or other resources. The finally block runs even when an exception occurs.
45. What is a Custom Exception in Java?
A custom exception is a user-defined exception created for a specific application requirement.
Developers create custom exceptions by extending Exception or RuntimeException. They are useful when business rules need clear error messages.
Example:
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}
46. What is the Difference Between Exception and Error?
| Exception | Error |
| Can usually be handled | Usually cannot be handled |
| Caused by application issues | Caused by serious system issues |
| Example: IOException | Example: OutOfMemoryError |
| Recovery is possible | Recovery is difficult |
47. What is Multithreading in Java?
Multithreading in Java allows multiple threads to run at the same time.
It helps improve performance in tasks like file processing, background jobs, API calls, and server-side applications. Java supports multithreading through the Thread class and Runnable interface.
48. What is the Difference Between Process and Thread?
| Process | Thread |
| Independent program in execution | Small unit inside a process |
| Has separate memory | Shares memory with other threads |
| Heavyweight | Lightweight |
| Slower communication | Faster communication |
49. What is the Thread Lifecycle in Java?
A Java thread moves through different states during execution.
The main thread states are New, Runnable, Running, Waiting, Timed Waiting, Blocked, and Terminated. Understanding the thread lifecycle helps developers debug concurrency issues.
50. What is Synchronization in Java?
Synchronization controls access to shared resources in a multithreaded program.
It prevents multiple threads from changing the same data at the same time. Java supports synchronization using the synchronized keyword.
51. What is the Difference Between wait() and sleep() in Java?
| wait() | sleep() |
| Releases the lock | Does not release the lock |
| Used for thread communication | Used to pause execution |
| Called on an object | Called on Thread |
| Must be inside synchronized block | No synchronized block required |
52. What is Deadlock in Java?
A deadlock in Java occurs when two or more threads are blocked forever because each thread is waiting for a resource locked by another thread.
It usually happens in multithreaded programs when one thread holds Lock A and waits for Lock B, while another thread holds Lock B and waits for Lock A. Since neither thread releases its current lock, both remain stuck permanently.
Deadlock can stop critical parts of a Java application, especially in systems that use synchronization, shared resources, database connections, or file locks. It can be prevented by acquiring locks in a fixed order, avoiding nested locks where possible, using lock timeouts, and keeping synchronized blocks as small as possible.
53. How Can Deadlock Be Prevented in Java?
Deadlock can be prevented by using a fixed lock order, avoiding nested locks, using timeout-based locking, and keeping synchronized blocks small.
Good thread design also helps reduce deadlock risk in enterprise Java applications.
54. What is the Difference Between Runnable and Callable?
| Runnable | Callable |
| Does not return a result | Returns a result |
| Cannot throw checked exceptions directly | Can throw checked exceptions |
| Uses run() method | Uses call() method |
| Used with Thread or Executor | Used with ExecutorService |
55. What is ExecutorService in Java?
ExecutorService is a Java concurrency framework used to manage thread execution.
It helps create thread pools, submit tasks, control background jobs, and manage thread lifecycle. It is better than creating many threads manually.
56. What is Garbage Collection in Java?
Garbage collection in Java is the process of removing unused objects from memory automatically.
The JVM identifies objects that are no longer referenced and clears them from heap memory. This helps reduce memory leaks and improves application stability.
57. What is the Difference Between Stack and Heap Memory in Java?
| Stack Memory | Heap Memory |
| Stores method calls and local variables | Stores objects |
| Smaller in size | Larger in size |
| Faster access | Slower than stack |
| Memory is cleared after method execution | Managed by garbage collector |
58. What is the final Keyword in Java?
The final keyword in Java is used to apply restrictions on variables, methods, and classes. It helps protect values, method behavior, and class design from unwanted modification.
A final variable can be assigned only once. After initialization, its value cannot be changed, which makes it useful for constants and fixed configuration values.
A final method cannot be overridden by a subclass. This is useful when a parent class method contains important logic that should remain unchanged in the inheritance hierarchy.
A final class cannot be extended by another class. This prevents inheritance and is commonly used when a class must remain secure, stable, or immutable, such as Java’s String class.
59. What is the Difference Between final, finally, and finalize?
| final | finally |
| Keyword | Block |
| Restricts changes | Runs cleanup code |
| Used with variables, methods, classes | Used with exception handling |
60. What is String Immutability in Java?
String immutability means a String object cannot be modified after it is created. Once a string value is stored in memory, its internal character sequence remains unchanged.
When an operation like concatenation, replacement, or trimming is performed, Java does not update the existing Stringobject. Instead, it creates a new String object with the modified value, while the original object remains the same.
This design makes String safe for use in the String Pool, improves memory optimization through reuse, protects sensitive data such as class names and file paths, and supports thread safety because multiple threads can share the same Stringobject without synchronization issues.
Advanced-Level Java Developer Interview Questions and Answers
61. What is the Java Memory Model?
The Java Memory Model defines how Java threads interact with memory. It explains how variables are read, written, cached, and made visible across threads.
Advanced Java developers use it to understand visibility, ordering, and safe communication between threads.
class SharedData {
private boolean running = true;
void stop() {
running = false;
}
void runTask() {
while (running) {
// may not see updated value immediately
}
}
}
Without proper visibility control, one thread may not see changes made by another thread.
62. What is the volatile Keyword in Java?
The volatile keyword tells the JVM that a variable must always be read from main memory.
It is useful when one thread updates a value and another thread needs to see the latest value.
class TaskRunner {
private volatile boolean running = true;
public void stop() {
running = false;
}
public void run() {
while (running) {
System.out.println("Running...");
}
}
}
volatile improves visibility, but it does not make compound operations fully atomic.
63. What is the Difference Between synchronized and ReentrantLock?
| synchronized | ReentrantLock |
| Built-in Java keyword | Lock class from concurrency package |
| Lock release is automatic | Lock release must be manual |
| Less flexible | More control over locking |
| No timeout support | Supports timeout and fairness |
Example:
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private final ReentrantLock lock = new ReentrantLock();
private int count = 0;
void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
ReentrantLock is useful when developers need advanced lock control.
64. What is ThreadLocal in Java?
ThreadLocal gives each thread its own separate copy of a variable.
It is often used for request context, user sessions, transaction IDs, and security context in backend Java applications.
class UserContext {
private static final ThreadLocal<String> userId = new ThreadLocal<>();
static void setUserId(String id) {
userId.set(id);
}
static String getUserId() {
return userId.get();
}
static void clear() {
userId.remove();
}
}
remove() is important because thread pools reuse threads.
65. What is CompletableFuture in Java?
CompletableFuture is used for asynchronous programming in Java.
It allows tasks to run in the background and lets developers combine, transform, or handle results later.
import java.util.concurrent.CompletableFuture;
public class Demo {
public static void main(String[] args) {
CompletableFuture<String> future =
CompletableFuture.supplyAsync(() -> "Java")
.thenApply(result -> result + " Developer");
System.out.println(future.join());
}
}
It is useful for API calls, background jobs, and non-blocking workflows.
66. What is the Fork/Join Framework in Java?
The Fork/Join Framework splits a large task into smaller subtasks and executes them in parallel.
It is useful for CPU-heavy operations where the task can be divided recursively.
import java.util.concurrent.RecursiveTask;
class SumTask extends RecursiveTask<Integer> {
private final int[] numbers;
private final int start, end;
SumTask(int[] numbers, int start, int end) {
this.numbers = numbers;
this.start = start;
this.end = end;
}
protected Integer compute() {
if (end - start <= 2) {
int sum = 0;
for (int i = start; i < end; i++) sum += numbers[i];
return sum;
}
int mid = (start + end) / 2;
SumTask left = new SumTask(numbers, start, mid);
SumTask right = new SumTask(numbers, mid, end);
left.fork();
return right.compute() + left.join();
}
}
It follows the divide-and-conquer approach.
67. What is Reflection in Java?
Reflection allows Java programs to inspect classes, methods, fields, and constructors at runtime.
Frameworks like Spring and Hibernate use reflection internally.
class Employee {
private String name;
}
public class ReflectionDemo {
public static void main(String[] args) {
Class<?> clazz = Employee.class;
System.out.println(clazz.getName());
System.out.println(clazz.getDeclaredFields()[0].getName());
}
}
Reflection is powerful, but it can affect performance and security.
68. What are Java Annotations?
Annotations provide metadata about code.
They are widely used in frameworks, testing tools, ORM tools, and dependency injection systems.
@interface Audit {
String value();
}
@Audit("User login tracking")
class LoginService {
}
Annotations do not directly execute logic. Tools and frameworks read them to decide behavior.
69. What is a Custom Annotation in Java?
A custom annotation is a developer-defined annotation used to attach metadata to classes, methods, or fields.
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface LogExecutionTime {
}
class PaymentService {
@LogExecutionTime
void processPayment() {
System.out.println("Payment processed");
}
}
Custom annotations are useful in logging, validation, authorization, and framework-level programming.
70. What is Serialization in Java?
Serialization converts an object into a byte stream.
The byte stream can be stored in a file, sent over a network, or transferred between services.
import java.io.Serializable;
class Employee implements Serializable {
private String name;
private int age;
Employee(String name, int age) {
this.name = name;
this.age = age;
}
}
Deserialization converts the byte stream back into an object.
71. What is serialVersionUID in Java?
serialVersionUID is a unique version ID used during serialization and deserialization.
It checks whether the serialized object and class definition are compatible.
import java.io.Serializable;
class Customer implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
}
A mismatch can cause InvalidClassException.
72. What is a ClassLoader in Java?
A ClassLoader loads Java classes into JVM memory at runtime.
Java uses class loaders for application classes, system classes, libraries, plugins, and application server environments.
public class ClassLoaderDemo {
public static void main(String[] args) {
ClassLoader loader = ClassLoaderDemo.class.getClassLoader();
System.out.println(loader);
}
}
ClassLoader knowledge is useful in debugging classpath and deployment issues.
73. What is the Difference Between ClassNotFoundException and NoClassDefFoundError?
| ClassNotFoundException | NoClassDefFoundError |
| Checked exception | Error |
| Happens during dynamic class loading | Happens when class was present earlier but missing at runtime |
| Often caused by Class.forName() | Often caused by classpath or dependency issues |
| Can be handled | Usually indicates deployment failure |
These errors are common in enterprise Java applications with complex dependencies.
74. What is JIT Compilation in Java?
JIT compilation means Just-In-Time compilation.
The JVM uses JIT to convert frequently executed bytecode into native machine code during runtime.
public class HotCode {
public static void main(String[] args) {
for (int i = 0; i < 1_000_000; i++) {
calculate(i);
}
}
static int calculate(int num) {
return num * num;
}
}
Repeatedly used code can become faster after JVM optimization.
75. What is Escape Analysis in Java?
Escape analysis is a JVM optimization technique.
It checks whether an object is used only inside a method or escapes outside that method.
class EscapeDemo {
int calculate() {
Point p = new Point(10, 20);
return p.x + p.y;
}
}
class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
The JVM may optimize memory allocation when an object does not escape.
76. What is Metaspace in Java?
Metaspace stores class metadata in Java.
It replaced PermGen from Java 8 onward. Metaspace grows dynamically, but excessive class loading can still create memory problems.
public class MetaspaceDemo {
public static void main(String[] args) {
System.out.println(String.class.getClassLoader());
System.out.println(MetaspaceDemo.class.getClassLoader());
}
}
Metaspace issues often appear in applications that load many classes dynamically.
77. What is the Difference Between Shallow Copy and Deep Copy?
| Shallow Copy | Deep Copy |
| Copies object references | Copies actual nested objects |
| Shared nested objects remain linked | Nested objects become independent |
| Faster | More memory-intensive |
| Risky for mutable objects | Safer for complex objects |
Example:
class Address {
String city;
}
class User {
String name;
Address address;
}
A shallow copy may share the same Address object between two users.
78. What are Generics in Java?
Generics allow developers to write reusable and type-safe code.
They reduce the need for manual casting and help catch type errors during compilation.
class Box<T> {
private T value;
void setValue(T value) {
this.value = value;
}
T getValue() {
return value;
}
}
Usage:
Box<String> box = new Box<>();
box.setValue("Java");
79. What is Type Erasure in Java?
Type erasure means generic type information is removed during compilation.
Java uses generics for compile-time safety, but most generic details are not available at runtime.
import java.util.*;
public class TypeErasureDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
List<Integer> numbers = new ArrayList<>();
System.out.println(names.getClass() == numbers.getClass());
}
}
This prints true because both become ArrayList at runtime.
80. What is a Bounded Type Parameter in Java?
A bounded type parameter restricts the type that can be used with generics.
class Calculator<T extends Number> {
double square(T value) {
return value.doubleValue() * value.doubleValue();
}
}
Here, T can be Integer, Double, Float, or another subclass of Number.
Bounded types improve type safety in reusable Java code.
81. What is PECS in Java Generics?
PECS stands for Producer Extends, Consumer Super.
It helps developers decide when to use extends and super with wildcards.
import java.util.*;
class Demo {
static double sum(List<? extends Number> numbers) {
double total = 0;
for (Number n : numbers) total += n.doubleValue();
return total;
}
static void addNumbers(List<? super Integer> numbers) {
numbers.add(10);
numbers.add(20);
}
}
Use extends when reading values. Use super when adding values.
82. What is a Spliterator in Java?
A Spliterator is used to traverse and split data for parallel processing.
It is more advanced than a normal iterator because it can divide data into parts.
import java.util.*;
public class SpliteratorDemo {
public static void main(String[] args) {
List<String> names = List.of("Amit", "Riya", "John");
Spliterator<String> spliterator = names.spliterator();
spliterator.forEachRemaining(System.out::println);
}
}
Spliterators are used internally by Java streams.
83. What is a Method Handle in Java?
A MethodHandle is a typed, directly executable reference to a method, constructor, or field.
It is more flexible and often faster than reflection for repeated method calls.
import java.lang.invoke.*;
public class MethodHandleDemo {
public static void main(String[] args) throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle handle = lookup.findStatic(
Math.class,
"max",
MethodType.methodType(int.class, int.class, int.class)
);
int result = (int) handle.invoke(10, 20);
System.out.println(result);
}
}
Method handles are used in advanced JVM and framework-level programming.
84. What is the Difference Between Reflection and MethodHandle?
| Reflection | MethodHandle |
| Older runtime inspection API | Newer method invocation API |
| More general | More direct and typed |
| Often slower for repeated calls | Usually better for repeated calls |
| Common in frameworks | Common in JVM-level operations |
Reflection is easier to understand. MethodHandle is better for advanced dynamic invocation.
85. What are Records in Java?
Records are special Java classes used to create immutable data carrier objects.
They reduce boilerplate code by automatically generating constructor, accessor methods, equals(), hashCode(), and toString().
record Employee(String name, int age) {
}
public class RecordDemo {
public static void main(String[] args) {
Employee employee = new Employee("Riya", 25);
System.out.println(employee.name());
System.out.println(employee);
}
}
Records are useful for DTOs, API responses, and read-only data models.
86. What are Sealed Classes in Java?
Sealed classes restrict which classes can extend or implement them.
They help developers control inheritance in complex domain models.
sealed class Payment permits CardPayment, UpiPayment {
}
final class CardPayment extends Payment {
}
final class UpiPayment extends Payment {
}
Sealed classes make code more predictable and safer.
87. What is Pattern Matching in Java?
Pattern matching simplifies conditional logic by combining type checking and variable extraction.
public class PatternDemo {
static void printLength(Object value) {
if (value instanceof String text) {
System.out.println(text.length());
}
}
}
It avoids unnecessary casting and makes code cleaner.
88. What is the Java Module System?
The Java Module System helps organize large applications into modules.
It was introduced in Java 9 to improve dependency control and application structure.
module com.example.app {
requires java.sql;
exports com.example.service;
}
Modules make Java applications easier to maintain at scale.
89. What is the Foreign Function and Memory API in Java?
The Foreign Function and Memory API allows Java programs to interact with native code and memory outside the JVM.
It is designed as a safer modern alternative to JNI for many use cases.
// Conceptual example
// Java can call native libraries and access off-heap memory
// using the Foreign Function and Memory API.
This is useful in high-performance systems, native integrations, and low-level libraries.
90. What are Virtual Threads in Java?
Virtual threads are lightweight threads designed for high-concurrency applications.
They make it easier to handle many blocking tasks without creating thousands of expensive platform threads.
public class VirtualThreadDemo {
public static void main(String[] args) throws InterruptedException {
Thread thread = Thread.startVirtualThread(() -> {
System.out.println("Running in virtual thread");
});
thread.join();
}
}
Virtual threads are useful for scalable server-side Java applications, especially when handling many requests.
Scenario-Based Java Developer Interview Questions and Answers
91. A Spring Boot API is taking too long to respond. How would you debug it?
I would first check logs, response time, database queries, external API calls, and server resource usage.
Slow Java APIs often happen because of unoptimized SQL queries, missing indexes, large payloads, slow third-party services, or blocking operations. I would use tools like application logs, Spring Boot Actuator, APM tools, and database query analysis to find the exact bottleneck.
92. A user clicks the payment button twice. How would you prevent duplicate payment processing?
I would use idempotency.
Each payment request should have a unique idempotency key. The backend should check whether the same key was already processed before creating a new payment.
if (paymentRepository.existsByRequestId(requestId)) {
return existingPaymentResponse;
}
processPayment(request);
This prevents duplicate transactions in real-world Java backend systems.
93. A database query works fine in testing but becomes slow in production. What would you check?
I would check data volume, indexes, query execution plan, joins, pagination, and database locks.
A query may work fast with 100 records but become slow with 10 lakh records. I would also check whether the Java application is fetching unnecessary columns or loading too many related entities.
94. Your Spring Boot service is returning too much data in one API response. What would you do?
I would add pagination, filtering, and response DTOs.
Large API responses increase memory usage and slow down both backend and frontend performance.
Page<User> users = userRepository.findAll(PageRequest.of(0, 20));
A clean Java API should return only the required data for the current screen or operation.
95. A Java application frequently runs out of database connections. How would you solve it?
I would check whether connections are being closed properly and review the connection pool configuration.
In Spring Boot, I would inspect HikariCP settings, long-running queries, transaction boundaries, and connection leaks. Poor connection handling can slow down the full application.
96. A REST API sometimes saves partial data when an error occurs. How would you fix it?
I would use proper transaction management.
In Spring Boot, @Transactional ensures that all database operations inside a method succeed together. The transaction rolls back when an error occurs.
@Transactional
public void placeOrder(OrderRequest request) {
saveOrder(request);
updateInventory(request);
savePayment(request);
}
This keeps data consistent in Java enterprise applications.
97. A Java service depends on another service that often fails. How would you protect your application?
I would use timeout handling, retries, fallback logic, and a circuit breaker.
A Java service should not keep waiting forever for a failing external service. Tools like Resilience4j can help prevent cascading failures in microservice-based systems.
98. A login API is working, but users can access protected APIs without proper validation. What would you check?
I would check authentication, authorization, token validation, role checks, and security filters.
A secure Java backend should verify every protected request. JWT expiry, signature validation, user roles, and endpoint permissions must be handled correctly.
99. Your application logs are full of errors, but they do not explain the actual issue. What would you improve?
I would improve structured logging, exception messages, request IDs, and log levels.
Good Java application logs should show what failed, where it failed, and which request caused it. I would avoid logging sensitive data such as passwords, tokens, and payment details.
100. A frequently used API is putting heavy load on the database. How would you optimize it?
I would use caching where the data does not change often.
For example, product categories, country lists, configuration data, and user permissions can be cached.
@Cacheable("products")
public Product getProductById(Long id) {
return productRepository.findById(id).orElseThrow();
}
Caching reduces repeated database calls and improves Java application performance.
Java Interview Tips
- Start with the Core Definition: Give a clean one-line definition first. Then explain where the concept is used in Java applications.
- Add One Practical Example: Connect every answer to backend systems, APIs, databases, threads, memory, or Spring Boot use cases.
- Do Not Stop at Syntax: Interviewers want to know why a concept matters. Explain the purpose, behavior, and real-world impact.
- Compare Similar Concepts Clearly:
Prepare differences like ArrayList vs LinkedList, throw vs throws, wait vs sleep, and final vs finally. - Explain JVM Topics Slowly: For memory, garbage collection, JIT, metaspace, and class loading, use simple flow-based explanations.
- Prepare Concurrency Carefully: Multithreading questions are common. Be ready with synchronization, deadlock, volatile, ThreadLocal, and ExecutorService.
- Think Like a Backend Developer: For scenario questions, mention logs, database queries, API response time, connection pools, transactions, caching, and security checks.
- End Answers with Confidence: Close with a practical takeaway. Example: “This improves performance and keeps the application stable in production.”
Conclusion
Java interviews can feel challenging because they test both fundamentals and real-world development thinking. A strong answer is not only about defining a concept correctly. It is also about explaining how that concept works in backend systems, APIs, databases, memory management, and production environments.
This list of Top 100 Java Developer Interview Questions and Answers gives you a complete revision path from beginner-level basics to advanced JVM concepts and scenario-based problem-solving. Practice the code examples, understand the logic behind each answer, and explain every concept in your own words. That is what helps you sound confident, practical, and interview-ready.



Did you enjoy this article?