100 Most Frequently Asked Java Interview Questions & Answers
1. Core Java Fundamentals
1. What are the main features of Java?
Java is:
- Object-oriented
- Platform-independent through the JVM
- Strongly typed
- Garbage collected
- Multithreaded
- Secure
- Robust
- High-performance through JIT compilation
2. What is the difference between JDK, JRE, and JVM?
| Component | Purpose |
|---|---|
| JVM | Executes Java bytecode |
| JRE | JVM + libraries required to run Java applications |
| JDK | JRE + development tools such as javac, javadoc, jdb |
Modern JDK distributions generally no longer ship a separate JRE installation.
3. Why is Java platform-independent?
Java source code is compiled into bytecode:
Java Source
↓
javac
↓
Bytecode (.class)
↓
JVM
↓
Operating System
The same bytecode can run on different operating systems as long as an appropriate JVM exists.
4. Is Java completely object-oriented?
No. Java supports primitive types such as:
int
long
double
boolean
char
Therefore Java is not purely object-oriented.
5. What is the difference between == and .equals()?
== compares:
- primitive values, or
- object references
.equals() compares object equality according to the implementation.
String a = new String("Java");
String b = new String("Java");
a == b // false
a.equals(b) // true
6. What is the difference between primitive and reference types?
Primitive types store values directly:
Java
int age = 30;
Reference variables hold references to objects:
Java
Person person = new Person();
Java has eight primitive types:
byte, short, int, long,
float, double, char, boolean
7. What is autoboxing and unboxing?
Autoboxing converts primitive → wrapper:
Java
Integer x = 10;
Unboxing converts wrapper → primitive:
Java
int y = x;
8. What is the difference between final, finally, and finalize()?
final
- variable → cannot be reassigned
- method → cannot be overridden
- class → cannot be inherited
finally
Used for cleanup after exception handling.
try {
// ...
} finally {
// cleanup
}
finalize()
A deprecated mechanism historically associated with GC-based cleanup. It should not be used in modern Java.
9. What is immutability?
An immutable object cannot change its state after creation.
String is the classic example.
String s = "Java";
s.concat(" Programming");
The original String remains unchanged.
10. Why is String immutable in Java?
Main reasons include:
- Security
- Thread safety
- String pool optimization
- HashCode caching
- Safe use as
HashMapkeys
2. Object-Oriented Programming
11. What are the four pillars of OOP?
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
12. What is encapsulation?
Encapsulation combines data and behavior while restricting direct access to internal state.
class Account {
private double balance;
public double getBalance() {
return balance;
}
}
13. What is inheritance?
Inheritance allows a class to reuse or extend another class.
class Animal {
}
class Dog extends Animal {
}
Java supports single class inheritance.
14. Why doesn’t Java support multiple class inheritance?
To avoid ambiguity such as the diamond problem.
Instead, Java supports multiple interface inheritance:
class MyClass implements A, B {
}
15. What is polymorphism?
Polymorphism allows the same interface or parent type to represent different implementations.
Animal animal = new Dog();
animal.sound();
There are two major forms:
- Compile-time polymorphism → method overloading
- Runtime polymorphism → method overriding
16. What is method overloading?
Multiple methods with the same name but different parameter lists.
void calculate(int a) {}
void calculate(int a, int b) {}
Return type alone cannot distinguish overloaded methods.
17. What is method overriding?
A subclass provides a new implementation of a superclass method.
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
18. Overloading vs overriding?
| Overloading | Overriding |
|---|---|
| Compile time | Runtime |
| Same class usually | Parent/child classes |
| Different parameters | Same method signature |
| Return type can differ | Compatible return type |
19. Abstract class vs interface?
| Abstract Class | Interface |
|---|---|
| Can contain state | Primarily defines contract |
| Constructors allowed | No constructors |
| Instance fields allowed | Fields are implicitly constants |
| One class can extend one | Class can implement multiple |
Modern interfaces can also contain default, static, and private methods.
20. Can an abstract class have a constructor?
Yes.
abstract class Animal {
Animal() {
System.out.println("Created");
}
}
The constructor executes when a subclass is instantiated.
3. Java Memory & JVM
21. What is JVM?
The JVM executes Java bytecode and provides:
- Memory management
- Garbage collection
- JIT compilation
- Class loading
- Runtime security
22. What is the JVM architecture?
A simplified view:
Class Loader
↓
Bytecode
↓
Runtime Data Areas
↓
Execution Engine
↓
Native Interface
Important runtime areas include:
- Heap
- Thread stacks
- Metaspace
- Program Counter
- Native method stacks
23. Heap vs Stack?
Heap
- Objects
- Shared between threads
- Managed by GC
Stack
- Method frames
- Local variables
- Per-thread
- Automatically managed when methods return
24. What is Metaspace?
Metaspace stores JVM class metadata.
Since Java 8, Metaspace replaced the old PermGen space.
25. What is garbage collection?
Garbage collection automatically identifies objects that are no longer reachable and reclaims their memory.
26. Can Java have memory leaks?
Yes.
Java prevents many manual memory-management errors, but objects can remain reachable unnecessarily.
Example:
Java
static List<Object> cache = new ArrayList<>();
If objects are continually added and never removed, memory consumption can grow indefinitely.
27. What makes an object eligible for garbage collection?
An object becomes eligible when it is no longer reachable from GC roots.
For example:
Person p = new Person();
p = null;
The Person object may now become eligible for GC if no other references exist.
28. What are GC roots?
Typical GC roots include:
- Active thread stacks
- Static fields
- JNI references
- JVM internal references
29. What is JIT?
JIT means Just-In-Time compiler.
It identifies frequently executed bytecode and compiles it into native machine code at runtime.
This significantly improves performance for long-running applications.
30. What is escape analysis?
Escape analysis determines whether objects created by a method escape that method/thread.
The JVM may optimize allocations through techniques such as:
- Scalar replacement
- Lock elimination
- Stack allocation-like optimizations
4. String Questions
31. String vs StringBuilder vs StringBuffer?
| Type | Mutable | Thread-safe |
|---|---|---|
| String | No | Yes |
| StringBuilder | Yes | No |
| StringBuffer | Yes | Yes |
For most single-threaded concatenation, use StringBuilder.
32. What is the String pool?
The String pool stores canonical String instances so identical string literals can share objects.
String a = "Java";
String b = "Java";
a == b; // true
33. What happens with new String("Java")?
Java
String s = new String("Java");
A new String object is explicitly created, even if "Java" already exists in the String pool.
34. Why should String be used carefully as a HashMap key?
Because String is immutable and has stable hash codes, which actually makes it an excellent key.
The important point is that mutable keys are dangerous, not Strings.
35. How do you reverse a String?
String reversed =
new StringBuilder("Java")
.reverse()
.toString();
5. Collections
36. What is the Java Collections Framework?
It provides interfaces and implementations for storing and manipulating groups of objects.
Important interfaces:
Collection
├── List
├── Set
└── Queue
Map
37. ArrayList vs LinkedList?
ArrayList
- Backed by dynamic array
- Fast random access
- Generally better default choice
LinkedList
- Doubly linked list
- Efficient insertion/removal when positioned at the node
- Poor random access
- Often overused in practice
38. ArrayList vs Vector?
Vector is a legacy synchronized collection.
ArrayList is generally preferred for modern applications.
39. HashSet vs TreeSet vs LinkedHashSet?
| Collection | Ordering | Typical complexity |
|---|---|---|
| HashSet | None guaranteed | O(1) |
| LinkedHashSet | Insertion order | O(1) |
| TreeSet | Sorted | O(log n) |
40. HashMap vs Hashtable?
HashMap
- Not synchronized
- Allows one null key
- Allows null values
- Modern choice
Hashtable
- Legacy
- Synchronized
- Does not allow null keys/values
41. How does HashMap work internally?
Conceptually:
key
↓
hashCode()
↓
hash spreading
↓
bucket
↓
compare keys
↓
value
Modern Java implementations use buckets containing nodes and may convert heavily-collided buckets into balanced trees.
42. What happens if two keys have the same hash code?
They are placed in the same bucket.
HashMap then uses equals() to distinguish them.
Therefore:
hashCode() → locate bucket
equals() → identify exact key
43. Why must equals() and hashCode() be consistent?
If:
Java
a.equals(b)
is true, then:
Java
a.hashCode() == b.hashCode()
must also be true.
Otherwise hash-based collections may behave incorrectly.
44. What is a fail-fast iterator?
A fail-fast iterator attempts to detect structural modification during iteration and may throw:
Java
ConcurrentModificationException
Example:
for (String s : list) {
list.remove(s);
}
45. What is ConcurrentHashMap?
A thread-safe Map designed for concurrent access.
It provides much better concurrency than synchronizing an entire HashMap.
46. HashMap vs ConcurrentHashMap?
| HashMap | ConcurrentHashMap |
|---|---|
| Not thread-safe | Thread-safe |
| Allows null key/value | Does not allow null |
| Faster in non-concurrent use | Designed for concurrency |
47. What is CopyOnWriteArrayList?
A thread-safe list optimized for scenarios with:
- Many reads
- Few writes
Each structural write creates a new underlying array.
48. Comparable vs Comparator?
Comparable
Defines natural ordering inside the class:
Java
class Employee implements Comparable<Employee>
Comparator
Defines external/custom ordering:
Comparator<Employee> bySalary =
Comparator.comparing(Employee::getSalary);
49. What is PriorityQueue?
A queue where elements are ordered according to natural ordering or a supplied comparator.
It is commonly implemented using a binary heap.
50. What is Deque?
A double-ended queue.
Java
Deque<Integer> deque = new ArrayDeque<>();
Elements can be inserted or removed from either end.
6. Exception Handling
51. Checked vs unchecked exceptions?
Checked exceptions
- Checked at compile time
- Must be caught or declared
- Extend
Exception, excludingRuntimeException
Unchecked exceptions
- Extend
RuntimeException - Usually indicate programming errors or invalid runtime state
52. Error vs Exception?
Error generally represents serious JVM/system problems.
Examples:
OutOfMemoryError
StackOverflowError
Exceptions generally represent conditions an application may handle.
53. throw vs throws?
throw actually throws an exception:
Java
throw new IllegalArgumentException();
throws declares possible exceptions:
void read() throws IOException {
}
54. Can finally not execute?
Yes, for example if the JVM terminates abruptly:
Java
System.exit(0);
or the process crashes.
55. Can we have try without catch?
Yes, if there is a finally:
try {
// code
} finally {
// cleanup
}
56. What is try-with-resources?
It automatically closes resources implementing AutoCloseable.
try (BufferedReader reader =
new BufferedReader(new FileReader("file.txt"))) {
// use resource
}
57. What are suppressed exceptions?
When try-with-resources encounters an exception during resource closing while another exception is already being thrown, the closing exception can become a suppressed exception.
7. Java 8+ Features
58. What is a lambda expression?
A lambda provides a concise implementation of a functional interface.
Java
(a, b) -> a + b
59. What is a functional interface?
An interface with exactly one abstract method.
Examples:
Runnable
Callable
Predicate
Function
Consumer
Supplier
It can be annotated with:
Java
@FunctionalInterface
60. What is the Stream API?
Streams provide a declarative way to process collections and other data sources.
List<String> result =
names.stream()
.filter(n -> n.startsWith("A"))
.map(String::toUpperCase)
.toList();
61. Stream vs Collection?
A Collection:
- Stores data.
A Stream:
- Processes data.
A stream generally does not store its own elements.
62. Intermediate vs terminal operations?
Intermediate operations:
filter()
map()
sorted()
distinct()
They return another stream and are generally lazy.
Terminal operations:
collect()
toList()
count()
reduce()
forEach()
They trigger stream processing.
63. What is lazy evaluation in streams?
Intermediate operations don’t execute immediately.
Execution begins when a terminal operation is invoked.
64. map() vs flatMap()?
map() transforms one element into one result.
List<String> names =
users.stream()
.map(User::getName)
.toList();
flatMap() flattens nested structures.
orders.stream()
.flatMap(order -> order.getItems().stream())
65. What is Optional?
Optional<T> represents a value that may or may not exist.
Java
Optional<User> user = findUser(id);
It can make absence explicit and reduce accidental null handling.
66. Should Optional be used everywhere?
No.
It is primarily useful for expressing optional return values.
Using it excessively for:
- entity fields
- method parameters
- serialization models
can make APIs unnecessarily complicated.
67. What is method reference?
Instead of:
Java
names.forEach(name -> System.out.println(name));
you can write:
Java
names.forEach(System.out::println);
68. What is a default method?
An interface can provide an implementation:
interface Vehicle {
default void start() {
System.out.println("Starting");
}
}
This helped Java evolve interfaces without breaking existing implementations.
69. What is the difference between orElse() and orElseGet()?
Java
optional.orElse(createDefault());
The default expression is evaluated immediately.
Java
optional.orElseGet(() -> createDefault());
The supplier is evaluated only when needed.
8. Java 9–21
70. What are Java modules?
The Java Platform Module System was introduced in Java 9.
It allows applications to explicitly define module boundaries and dependencies.
Example:
module com.example.app {
requires java.sql;
exports com.example.api;
}
71. What are records?
Records provide concise syntax for immutable data carriers.
public record User(
Long id,
String name
) {}
The compiler generates accessors, constructor, equals(), hashCode(), and toString().
72. Are records completely immutable?
Records provide final components, but referenced objects can still be mutable.
For example:
Java
record User(List<String> roles) {}
The roles list itself may still be modified unless defensively copied.
73. What are sealed classes?
Sealed classes restrict which classes can extend or implement them.
public sealed interface Shape
permits Circle, Rectangle {
}
This is useful for controlled domain hierarchies.
74. What is pattern matching for instanceof?
Traditional:
if (obj instanceof String) {
String s = (String) obj;
}
Modern Java:
if (obj instanceof String s) {
System.out.println(s.length());
}
75. What is pattern matching for switch?
Modern Java allows more expressive type-based switch logic.
return switch (obj) {
case Integer i -> i * 2;
case String s -> s.length();
default -> 0;
};
76. What are virtual threads?
Virtual threads are lightweight JVM-managed threads designed for high-concurrency workloads, especially I/O-bound applications.
Introduced as a final feature in Java 21.
Example:
Thread.startVirtualThread(() -> {
// task
});
77. Virtual threads vs platform threads?
Platform thread
- Maps more directly to an OS thread
- More expensive
Virtual thread
- Managed by JVM
- Lightweight
- Can support very large numbers of concurrent tasks
- Particularly useful for blocking I/O
Virtual threads don’t make CPU-bound work inherently faster.
78. What is structured concurrency?
Structured concurrency treats related concurrent tasks as a single unit of work with clear lifetime and cancellation semantics.
It aims to make concurrent code easier to reason about and manage.
79. What are Scoped Values?
Scoped values provide a mechanism for sharing immutable contextual data with child execution contexts, particularly useful with modern concurrency models.
They are intended as a safer alternative to some uses of ThreadLocal.
80. What are switch expressions?
Older:
int result;
switch (status) {
case 1:
result = 100;
break;
default:
result = 0;
}
Modern:
int result = switch (status) {
case 1 -> 100;
default -> 0;
};
9. Multithreading & Concurrency
81. Process vs thread?
A process has its own memory space.
Threads are execution units within a process and typically share process memory.
82. How can you create a thread?
Common approaches:
new Thread(() -> {
// task
}).start();
or use an executor:
ExecutorService executor =
Executors.newFixedThreadPool(10);
For Java 21 applications, virtual threads may also be appropriate.
83. Runnable vs Callable?
Runnable:
Java
void run()
No return value.
Callable<T>:
Java
T call()
Can return a value and throw checked exceptions.
84. What is ExecutorService?
It manages asynchronous task execution using a pool or other execution strategy.
ExecutorService executor =
Executors.newFixedThreadPool(10);
Future<Integer> future =
executor.submit(() -> 42);
85. What is synchronization?
Synchronization controls concurrent access to shared mutable state.
synchronized void increment() {
count++;
}
It provides mutual exclusion and memory visibility guarantees.
86. synchronized vs Lock?
synchronized:
- Simple
- Built into language
- Automatically releases lock
Lock:
- More flexible
- Supports
tryLock() - Can support interruptible locking
- Allows multiple condition objects
87. What is volatile?
volatile ensures reads/writes go through memory visibility rules that make updates visible across threads.
Java
private volatile boolean running;
However, volatile does not make compound operations atomic.
Java
count++; // not atomic
88. What is AtomicInteger?
It provides atomic operations without explicit synchronization for supported operations.
AtomicInteger counter = new AtomicInteger();
counter.incrementAndGet();
89. What is a race condition?
A race condition occurs when program behavior depends on the unpredictable timing of concurrent operations.
Example:
Java
count++;
is not atomic.
90. What is deadlock?
Deadlock occurs when threads wait indefinitely for locks held by each other.
Example:
Thread A → Lock 1 → waits for Lock 2
Thread B → Lock 2 → waits for Lock 1
Common prevention techniques:
- Consistent lock ordering
- Lock timeouts
- Avoid unnecessary nested locks
91. What is livelock?
Threads are not blocked, but continually react to each other without making progress.
92. What is starvation?
A thread never gets enough access to CPU time or required resources because other threads continuously consume them.
10. Advanced Java / Design
93. What is dependency injection?
Dependency Injection means an object’s dependencies are supplied externally rather than created internally.
Instead of:
class OrderService {
private PaymentService service =
new PaymentService();
}
use:
class OrderService {
private final PaymentService service;
OrderService(PaymentService service) {
this.service = service;
}
}
Frameworks such as Spring automate this process.
94. What are SOLID principles?
S — Single Responsibility Principle
O — Open/Closed Principle
L — Liskov Substitution Principle
I — Interface Segregation Principle
D — Dependency Inversion Principle
Senior-level interviews frequently explore these through practical examples rather than definitions.
95. Composition vs inheritance?
Composition means building an object using other objects:
class Car {
private Engine engine;
}
Inheritance means establishing an “is-a” relationship:
class Dog extends Animal {
}
In many designs, composition is preferred over inheritance because it reduces coupling.
96. What is the Singleton pattern?
It ensures a class has a single instance.
A robust Java approach is often an enum:
enum Singleton {
INSTANCE
}
But in modern applications, dependency-injection frameworks often manage singleton lifecycle instead.
97. What is defensive copying?
Creating copies of mutable objects to protect encapsulation.
public List<String> getNames() {
return List.copyOf(names);
}
This prevents callers from modifying the internal mutable collection.
98. What is serialization?
Serialization converts an object’s state into a representation suitable for storage or transmission.
Java’s built-in serialization uses:
Java
Serializable
However, for modern distributed systems, JSON, Protocol Buffers, Avro, etc. are often preferred.
99. What is reflection?
Reflection allows Java applications to inspect and interact with classes, methods, fields, and constructors at runtime.
Frameworks such as Spring, Hibernate, and testing frameworks use reflection extensively.
Example:
Class<?> clazz = MyClass.class;
Method[] methods = clazz.getDeclaredMethods();
100. What makes a good Java application production-ready?
A strong senior-level answer should cover more than just clean code:
Clean Architecture
↓
Correctness
↓
Concurrency
↓
Performance
↓
Security
↓
Observability
↓
Testing
↓
Resilience
↓
Deployment
↓
Maintainability