Top 180 Core Java Interview Questions and Answers 2026
Oct 01, 2026 23 Min Read 71836 Views
(Last Updated)
Core Java interviews in 2026 test much more than whether you remember syntax or definitions. Interviewers want to know whether you understand how Java executes code, how object-oriented programming works in practice, which collection fits a particular problem, how concurrency issues occur, and what happens inside the JVM when an application runs.
The difficulty also changes with experience. Freshers may be asked about JDK, JVM, constructors, inheritance, Strings, and exception handling. Intermediate developers should be ready for collections, generics, Streams, functional interfaces, multithreading, and file handling. Experienced candidates are more likely to face questions about HashMap internals, the Java Memory Model, garbage collection, concurrency utilities, JVM performance, records, sealed classes, pattern matching, and virtual threads.
This guide covers 160 Core Java interview questions and answers for 2026, divided across beginner, intermediate, advanced, modern Java, and scenario-based levels. Use it as a progressive preparation guide rather than trying to memorize every answer word for word.
Quick Answer
Core Java interviews generally test these areas:
- Java Fundamentals: JDK, JRE, JVM, bytecode, variables, data types, operators, classes, and methods.
- Object-Oriented Programming: Encapsulation, inheritance, polymorphism, abstraction, constructors, interfaces, and abstract classes.
- Strings and Collections: String immutability, ArrayList, LinkedList, Set, Map, Queue, hashing, sorting, and iterators.
- Exceptions and Generics: Checked and unchecked exceptions, custom exceptions, generic classes, wildcards, and type erasure.
- Java 8+ Features: Lambda expressions, functional interfaces, Stream API, Optional, method references, and Date-Time API.
- Concurrency: Threads, synchronization, locks, atomic variables, executors, CompletableFuture, race conditions, and deadlocks.
- JVM Internals: Heap, stack, class loading, JIT compilation, garbage collection, memory leaks, and performance.
- Modern Java: Records, sealed classes, pattern matching, switch expressions, modules, and virtual threads.
Table of contents
- What Is Core Java?
- Beginner-Level Core Java Interview Questions
- What is Java?
- What are the main features of Java?
- Why is Java called platform-independent?
- What is the difference between JDK, JRE, and JVM?
- What is JVM?
- What is bytecode in Java?
- What is a class in Java?
- What is an object?
- What are the four pillars of OOP in Java?
- What is encapsulation?
- What is inheritance?
- What is polymorphism?
- What is abstraction?
- What is a constructor?
- What is a default constructor?
- Can constructors be inherited?
- Can constructors be overloaded?
- What is method overloading?
- What is method overriding?
- Method overloading vs method overriding: what is the difference?
- What is the this keyword?
- What is the super keyword?
- What are primitive data types in Java?
- Is String a primitive type?
- What are wrapper classes?
- What is autoboxing?
- What is unboxing?
- What is type casting?
- What is the static keyword?
- Can a static method access instance variables directly?
- Can this or super be used inside a static method?
- What is the final keyword?
- What is an interface?
- What is an abstract class?
- Abstract class vs interface: which should you use?
- What are access modifiers in Java?
- What is a package?
- What is the purpose of the main() method?
- Is Java pass-by-reference?
- What is an array in Java?
- Intermediate-Level Core Java Interview Questions
- Why is String immutable?
- What is the String pool?
- What is the difference between == and equals()?
- Why must hashCode() be consistent with equals()?
- What is StringBuilder?
- StringBuilder vs StringBuffer
- What is an exception?
- Checked vs unchecked exceptions
- What is the difference between throw and throws?
- What is a finally block?
- What is try-with-resources?
- Can one catch block handle multiple exception types?
- What is a custom exception?
- What is the Java Collections Framework?
- What is ArrayList?
- What is LinkedList?
- ArrayList vs LinkedList
- What is a Set?
- What is HashSet?
- What is a Map?
- What is HashMap?
- Can HashMap store null?
- How does HashMap handle collisions?
- What is LinkedHashMap?
- What is TreeMap?
- HashMap vs TreeMap
- What is a Queue?
- What is Deque?
- Why is ArrayDeque preferred over Stack?
- What is PriorityQueue?
- What is Iterator?
- What is ListIterator?
- What is ConcurrentModificationException?
- What is Comparable?
- What is Comparator?
- Comparable vs Comparator
- What are generics?
- What is type erasure?
- What is a bounded generic type?
- What are wildcards in generics?
- What does PECS mean?
- What is an enum?
- What is an inner class?
- What is a static nested class?
- What is an immutable class?
- Advanced Core Java Interview Questions
- What is a lambda expression?
- What is a functional interface?
- What does @FunctionalInterface do?
- What is a method reference?
- What is the Stream API?
- Is Stream a collection?
- What are intermediate Stream operations?
- What are terminal operations?
- What is lazy evaluation in Streams?
- What is map()?
- What is flatMap()?
- map() vs flatMap()
- What is reduce()?
- What is Optional?
- orElse() vs orElseGet()
- Should Optional replace every null?
- What is multithreading?
- How can tasks be executed concurrently in Java?
- Runnable vs Callable
- What is ExecutorService?
- Why use a thread pool?
- What is synchronization?
- Is synchronized reentrant?
- What is a race condition?
- What is deadlock?
- How can deadlock risk be reduced?
- What does volatile do?
- volatile vs synchronized
- What are atomic classes?
- AtomicLong vs LongAdder
- What is ConcurrentHashMap?
- Why does ConcurrentHashMap not allow null keys or values?
- What is CompletableFuture?
- thenApply() vs thenCompose()
- What is the Fork/Join Framework?
- JVM, Memory, and Modern Java Interview Questions
- What is heap memory?
- What is stack memory?
- Heap vs Stack
- What is Metaspace?
- What is garbage collection?
- Can Java applications have memory leaks?
- What is a strong reference?
- What are weak references?
- What is a class loader?
- What is parent delegation in class loading?
- What is JIT compilation?
- What is reflection?
- What are the disadvantages of reflection?
- What are annotations?
- What is a record?
- Are records deeply immutable?
- What is a sealed class?
- What do sealed, final, and non-sealed mean?
- What is pattern matching for instanceof?
- What is a switch expression?
- What is yield in a switch expression?
- What are text blocks?
- What is the Java Module System?
- What is module-info.java?
- What are virtual threads?
- When are virtual threads useful?
- Platform threads vs virtual threads
- Should virtual threads be pooled?
- What is thread pinning?
- Which modern Java features should candidates know in 2026?
- Scenario-Based Core Java Interview Questions
- You inserted an object into a HashMap but cannot retrieve it later. What would you check?
- A HashMap suddenly becomes slow with a custom key class. What would you investigate?
- A HashSet contains what appear to be duplicate Employee objects. Why?
- Two threads increment a shared counter 10,000 times each, but the final value is lower than 20,000. Why?
- Two application threads freeze while waiting for each other. How would you investigate it?
- An ArrayList is being updated by multiple threads and behaves inconsistently. What is wrong?
- Your code throws ConcurrentModificationException while removing items from a list. How would you fix it?
- A loop performs thousands of String concatenations. How would you improve it?
- Your application runs out of heap even though Java has garbage collection. What would you do?
- A recursive method produces StackOverflowError. What happened?
- Your application has many blocking HTTP requests and platform threads are exhausted. What would you consider?
- Would you use virtual threads for a CPU-heavy image-processing task?
- A parallel Stream is slower than a normal Stream. Why?
- A parallel Stream produces incorrect results while adding values to a shared ArrayList. Why?
- Your Stream pipeline contains filter() and map(), but nothing happens. Why?
- A production service has excellent average latency but occasional extreme pauses. What Java areas would you investigate?
- An application becomes slower after changing every collection operation to parallel Stream. Why?
- A method returns null, and callers contain many defensive null checks. How might you redesign it?
- You have two Employee sorting requirements: salary and joining date. Comparable or Comparator?
- Your application needs an immutable list. Is Collections.unmodifiableList() enough?
- A record stores a mutable List. Can callers change the record's apparent state?
- A synchronized method becomes a bottleneck. What would you do?
- Would ConcurrentHashMap make an entire multi-step business transaction thread-safe?
- Your validation code catches Exception everywhere. Why can that be problematic?
- A catch block is empty. Why is that dangerous?
- A file occasionally remains open after processing fails. What would you change?
- You have 50 independent remote service calls. How might you execute them concurrently?
- A CompletableFuture pipeline produces nested futures. What should you change?
- A method uses orElse(expensiveOperation()), but the expensive operation runs even when Optional contains a value. Why?
- Your manager asks you to improve Java application performance immediately. Would you start rewriting code?
- How to Prepare for a Core Java Interview
- What Core Java Topics Should Freshers Prioritize?
- What Should Experienced Java Developers Prepare Differently?
- What Do Interviewers Look for in Core Java Candidates?
- How Should You Answer Scenario-Based Java Interview Questions?
- Conclusion
- FAQs
- How should I prepare for a Core Java interview in 2026?
- What is the best trick for answering Core Java interview questions?
- What mistakes should I avoid in a Java interview?
- How can freshers perform better in Java interviews?
- How should experienced developers prepare for Java scenario questions?
What Is Core Java?
Core Java refers to the fundamental Java language features and Java SE APIs used to develop general-purpose applications.
It includes concepts such as object-oriented programming, classes, interfaces, exception handling, collections, generics, Streams, multithreading, file handling, networking, JVM internals, and memory management.
Core Java provides the foundation required before moving into technologies such as Spring, Hibernate, Jakarta EE, microservices, and enterprise Java development.
Beginner-Level Core Java Interview Questions
1. What is Java?

Java is a high-level, class-based programming language commonly used for backend systems, enterprise applications, desktop software, Android-related development, cloud services, and distributed applications.
Java source code is compiled into bytecode that can run on any compatible Java Virtual Machine, which provides much of Java’s platform independence.
2. What are the main features of Java?
Java provides several features that make it suitable for large software applications:
- Platform Independence: Compiled Java bytecode can run on different operating systems with compatible JVMs.
- Object-Oriented Programming: Java supports encapsulation, inheritance, polymorphism, and abstraction.
- Automatic Memory Management: Garbage collection manages unreachable objects.
- Strong Typing: Types are checked primarily at compile time.
- Multithreading: Java provides built-in APIs for concurrent programming.
- Exception Handling: Runtime problems can be represented and handled systematically.
- Rich Standard Library: Java SE provides APIs for collections, I/O, networking, concurrency, and more.
3. Why is Java called platform-independent?
Java code is normally compiled into JVM bytecode instead of directly into operating-system-specific machine instructions.
The process can be visualized as:
Java Source Code → Java Compiler → Bytecode → JVM → Machine Code
The same bytecode can therefore run on Windows, Linux, macOS, or another environment that provides a compatible JVM.
4. What is the difference between JDK, JRE, and JVM?
| Component | Purpose |
| JVM | Executes Java bytecode and manages runtime activities such as memory and garbage collection. |
| JRE | Conceptually provides the JVM and libraries required to run Java applications. |
| JDK | Provides the tools needed to develop Java applications, including the compiler and runtime components. |
Modern JDK distributions are generally used for both development and runtime deployment, so standalone JRE packaging is less central than it was in older Java versions.
5. What is JVM?
JVM stands for Java Virtual Machine. It provides the runtime environment in which Java bytecode executes.
The JVM handles responsibilities such as:
- Loading classes
- Verifying bytecode
- Managing memory
- Executing bytecode
- Performing garbage collection
- Supporting JIT compilation
- Managing threads
6. What is bytecode in Java?
Bytecode is the intermediate instruction format created by the Java compiler.
For example:
javac Employee.java
creates:
Employee.class
The .class file contains bytecode that can be executed by a compatible JVM.
7. What is a class in Java?
A class is a blueprint that defines the data and behavior associated with objects.
For example:
class Employee {
String name;
void work() {
System.out.println(“Working”);
}
}
Here, name defines state while work() defines behavior.
8. What is an object?
An object is an instance of a class created during program execution.
For example:
Employee employee = new Employee();
The object has three important characteristics:
- Identity: Distinguishes it from other objects.
- State: Stored in its fields.
- Behavior: Defined through methods.
9. What are the four pillars of OOP in Java?
The four major object-oriented programming principles are:
- Encapsulation: Restricts direct access to internal object state.
- Inheritance: Allows one class to derive behavior from another.
- Polymorphism: Allows the same interface to represent different implementations.
- Abstraction: Exposes essential behavior while hiding unnecessary implementation details.
10. What is encapsulation?

Encapsulation combines related state and behavior inside a class while restricting direct access to internal data. It is an essential concept for a Java developer because it helps protect data and maintain controlled access within applications.
A common implementation uses private fields with controlled methods:
class Account {
private double balance;
public double getBalance() {
return balance;
}
}
This prevents other classes from arbitrarily changing balance.
11. What is inheritance?
Inheritance allows a subclass to reuse and extend accessible behavior from a superclass.
class Vehicle {
void start() {
System.out.println(“Vehicle started”);
}
}
class Car extends Vehicle {
}
Car can use inherited behavior from Vehicle.
12. What is polymorphism?
Polymorphism means that one interface, reference type, or method name can represent different behaviors.
Java commonly demonstrates polymorphism through:
| Type | Example |
| Compile-time polymorphism | Method overloading |
| Runtime polymorphism | Method overriding |
Runtime polymorphism allows the JVM to select an overridden implementation based on the actual object.
13. What is abstraction?
Abstraction focuses on what an object should do rather than exposing every implementation detail.
Java mainly provides abstraction through:
- Abstract classes
- Interfaces
For example, a Payment interface may define pay() without specifying how card, UPI, or wallet payments perform the operation internally.
14. What is a constructor?
A constructor initializes an object when it is created.
class User {
String name;
User(String name) {
this.name = name;
}
}
A constructor has the same name as its class and does not declare a return type.
15. What is a default constructor?
If a class declares no constructor, the compiler can provide a no-argument constructor automatically.
However, once you explicitly declare any constructor, the compiler does not automatically add that default constructor.
16. Can constructors be inherited?
No. Constructors belong specifically to the class in which they are declared.
A subclass can invoke a superclass constructor using:
super();
or:
super(arguments);
17. Can constructors be overloaded?
Yes. A class can declare multiple constructors as long as their parameter lists differ.
User() {
}
User(String name) {
}
User(String name, int age) {
}
This allows objects to be initialized in different ways.
18. What is method overloading?
Method overloading means defining multiple methods with the same name but different parameter lists.
void print(int value) { }
void print(String value) { }
The compiler determines which method to call based on the arguments.
19. What is method overriding?
Method overriding occurs when a subclass provides its own implementation of an inherited instance method.
class Animal {
void sound() {
System.out.println(“Animal sound”);
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println(“Bark”);
}
}
The actual object’s type determines which overridden implementation runs.
20. Method overloading vs method overriding: what is the difference?
| Method Overloading | Method Overriding |
| Usually occurs in the same class | Requires inheritance |
| Same method name | Same compatible method signature |
| Parameter list must differ | Parameters remain compatible with the overridden method |
| Resolved primarily at compile time | Resolved through runtime dispatch |
| Supports compile-time polymorphism | Supports runtime polymorphism |
21. What is the this keyword?
this refers to the current object.
It is commonly used to:
- Access instance variables: this.name
- Resolve naming conflicts: Distinguish fields from parameters.
- Call another constructor: this(…)
- Pass the current object: Supply it as an argument where required.
22. What is the super keyword?
super refers to the immediate superclass portion of the current object.
It can be used to:
super.methodName();
access superclass behavior, or:
super();
invoke a superclass constructor.
23. What are primitive data types in Java?
Java has eight primitive data types:
| Primitive | Typical Purpose |
| byte | Small integers |
| short | Small integer values |
| int | General integer calculations |
| long | Large integers |
| float | Single-precision floating-point values |
| double | Double-precision floating-point values |
| char | UTF-16 code unit |
| boolean | true or false |
24. Is String a primitive type?
No. String is a class from java.lang.
For example:
String language = “Java”;
language is a reference variable rather than a primitive value.
25. What are wrapper classes?
Wrapper classes provide object representations of primitive values.
Examples include:
- int → Integer
- long → Long
- double → Double
- boolean → Boolean
- char → Character
Wrapper classes are useful when an API requires objects, such as generic collections.
26. What is autoboxing?
Autoboxing automatically converts a primitive into its corresponding wrapper type.
Integer number = 10;
The primitive 10 is automatically boxed as an Integer.
27. What is unboxing?
Unboxing converts a wrapper object into its primitive value.
Integer number = 10;
int value = number;
Care is needed because unboxing a null wrapper produces a NullPointerException.
28. What is type casting?
Type casting converts a value or reference from one compatible type to another.
The two common primitive conversions are:
- Widening: Smaller type to a larger compatible type.
- Narrowing: Larger type to a smaller type.
int x = 10;
double y = x; // widening
double a = 9.8;
int b = (int) a; // narrowing
29. What is the static keyword?
A static member belongs to the class rather than a particular object.
class Counter {
static int count;
}
All Counter objects access the same count field.
30. Can a static method access instance variables directly?
No.
A static method has no implicit current object. It therefore needs an object reference before accessing instance state.
static void show() {
Employee e = new Employee();
System.out.println(e.name);
}
31. Can this or super be used inside a static method?
No. Both refer to object-level contexts, while static methods belong to the class itself.
32. What is the final keyword?
The meaning depends on where final is used:
- Final variable: Cannot be reassigned after initialization.
- Final method: Cannot be overridden.
- Final class: Cannot be subclassed.
For a final reference, the reference cannot point to another object, but the referenced object may still be mutable.
33. What is an interface?

An interface defines a contract that implementing classes agree to follow.
Modern interfaces can contain:
- Abstract methods
- Default methods
- Static methods
- Private helper methods
- Constants
A class can implement multiple interfaces.
34. What is an abstract class?
An abstract class cannot be instantiated directly and may contain both abstract and concrete behavior.
For example:
abstract class Shape {
abstract double area();
void display() {
System.out.println(“Shape”);
}
}
It is useful when subclasses share common state or implementation.
35. Abstract class vs interface: which should you use?
| Abstract Class | Interface |
| Can hold instance state | Primarily defines behavior contracts |
| Can define constructors | Cannot be instantiated through constructors |
| A class can extend only one class | A class can implement multiple interfaces |
| Useful for closely related classes | Useful for capabilities across different classes |
Choose based on the design rather than assuming one is universally better.
36. What are access modifiers in Java?

Java provides four access levels:
- private: Accessible only inside the declaring class.
- Package-private: Accessible within the same package.
- protected: Accessible within the package and through inheritance in other packages under Java’s access rules.
- public: Accessible wherever the declaring type itself is accessible.
37. What is a package?
A package groups related classes and interfaces.
Packages help with:
- Organizing code
- Preventing naming collisions
- Managing access
- Building modular application structures
For example:
package com.company.payment;
38. What is the purpose of the main() method?
A traditional Java application uses:
public static void main(String[] args)
as its entry point.
The runtime can invoke this method without first constructing the containing class.
39. Is Java pass-by-reference?
No. Java is always pass-by-value.
For objects, the value being copied is the object reference.
This distinction matters because a method can modify the state of the referenced object, but reassigning its local reference does not change the caller’s reference.
40. What is an array in Java?
An array stores a fixed number of values of the same declared component type.
int[] scores = {90, 85, 88};
Its size is fixed after creation.
Intermediate-Level Core Java Interview Questions
41. Why is String immutable?
A String cannot change after creation. Operations such as concatenation produce another String rather than modifying the original object.
String immutability provides several benefits:
- Safe sharing: The same String can be reused without unexpected modification.
- String pooling: Literals can be shared efficiently.
- Stable hash codes: Useful when Strings are map keys.
- Thread safety: Immutable values are easier to share between threads.
- Security: Values such as paths and class names cannot be modified through a shared String reference.
42. What is the String pool?
The String pool stores interned Strings so identical values can sometimes share the same object.
String a = “Java”;
String b = “Java”;
Both literals generally reference the same pooled String.
However:
String c = new String(“Java”);
explicitly creates another String object.
43. What is the difference between == and equals()?
| == | equals() |
| For objects, compares references | Usually compares logical equality |
| Cannot be overridden | Can be overridden |
| Useful for identity checks | Used for value-based comparison when implemented |
| Works directly with primitives | Method belongs to objects |
For Strings, use equals() when comparing textual content.
44. Why must hashCode() be consistent with equals()?
If two objects are equal according to equals(), they must return the same hash code.
Otherwise, hash-based structures such as HashMap and HashSet may behave incorrectly because equal objects could be placed in incompatible buckets.
The core contract is:
a.equals(b) == true
→
a.hashCode() == b.hashCode()
The reverse is not required because different objects can have the same hash code.
45. What is StringBuilder?

StringBuilder is a mutable sequence of characters.
It is useful when a program repeatedly modifies or concatenates text:
StringBuilder builder = new StringBuilder();
builder.append(“Core “);
builder.append(“Java”);
This avoids creating a new immutable String for every intermediate modification.
46. StringBuilder vs StringBuffer
| StringBuilder | StringBuffer |
| Mutable | Mutable |
| Not synchronized | Methods provide synchronization |
| Usually faster in single-threaded use | Has synchronization overhead |
| Commonly preferred for local string construction | Useful only where its synchronization semantics are actually needed |
47. What is an exception?
An exception represents an abnormal condition that interrupts normal program execution.
For example:
int result = 10 / 0;
can produce an ArithmeticException.
Java’s exception system allows such failures to be propagated and handled systematically.
48. Checked vs unchecked exceptions
Checked and unchecked exceptions differ mainly in compile-time handling:
| Checked Exception | Unchecked Exception |
| Usually extends Exception but not RuntimeException | Extends RuntimeException |
| Must normally be caught or declared | No compile-time catch-or-declare requirement |
| Often represents recoverable external conditions | Often represents programming or state errors |
| Example: IOException | Example: NullPointerException |
49. What is the difference between throw and throws?
throw actually throws an exception:
throw new IllegalArgumentException(“Invalid age”);
throws declares that a method may propagate an exception:
void load() throws IOException {
}
50. What is a finally block?
finally contains cleanup logic associated with a try statement.
It commonly handles actions such as releasing resources.
However, it is not absolutely guaranteed to execute in every possible situation, such as abrupt JVM termination.
51. What is try-with-resources?
Try-with-resources automatically closes objects implementing AutoCloseable.
try (BufferedReader reader =
Files.newBufferedReader(path)) {
System.out.println(reader.readLine());
}
It is usually safer than manually closing resources in a finally block.
52. Can one catch block handle multiple exception types?
Yes. Java supports multi-catch:
catch (IOException | SQLException e) {
// handle
}
This is useful when different exceptions require identical handling.
53. What is a custom exception?
A custom exception represents an application-specific failure.
class InsufficientBalanceException extends Exception {
InsufficientBalanceException(String message) {
super(message);
}
}
Custom exceptions make failure conditions more meaningful than using generic exceptions everywhere.
54. What is the Java Collections Framework?
The Java Collections Framework provides standard interfaces and implementations for storing and manipulating groups of objects.
Its major interfaces include:
- List: Ordered values that can contain duplicates.
- Set: Unique values.
- Queue: Elements organized for processing.
- Deque: Elements accessible from both ends.
- Map: Key-value associations.
55. What is ArrayList?
ArrayList implements List using a resizable array.
Its major characteristics include:
- Fast indexed access
- Maintains insertion order
- Allows duplicate elements
- Permits null values
- Automatically grows its internal capacity when required
Inserting into the middle may require shifting later elements.
56. What is LinkedList?
LinkedList is a doubly linked implementation of both List and Deque.
Each element is represented by a node connected to neighboring nodes.
Indexed access requires traversal, making operations such as get(index) generally slower than ArrayList for random access.
57. ArrayList vs LinkedList
| Requirement | ArrayList | LinkedList |
| Random indexed access | Usually efficient | Requires traversal |
| Memory overhead | Lower per element | Higher due to node links |
| Add at end | Efficient amortized behavior | Efficient |
| Insert after already-located node | May shift elements | Link changes can be cheap |
| CPU cache locality | Generally better | Generally poorer |
| Implements Deque | No | Yes |
Do not choose LinkedList simply because an application performs insertions. The cost of locating the insertion point also matters.
58. What is a Set?
A Set stores unique elements according to the equality or ordering rules of the implementation.
Common implementations are:
- HashSet: Hash-based uniqueness.
- LinkedHashSet: Predictable encounter order.
- TreeSet: Sorted values.
59. What is HashSet?
HashSet provides hash-based storage for unique elements.
Internally, it uses a hash-based map structure, where set elements effectively serve as keys.
Average-time performance for basic operations is typically efficient when hashing behaves well.
60. What is a Map?
Map<K,V> stores key-value mappings.
For example:
Map<Integer, String> users = new HashMap<>();
users.put(1, “Asha”);
users.put(2, “Rahul”);
Each key maps to at most one value.
61. What is HashMap?
HashMap is a hash-based Map implementation.
When a key is inserted, Java uses its hash information to identify a bucket. Candidate keys inside that bucket are distinguished using equality comparisons.
A good HashMap key therefore needs stable and compatible hashCode() and equals() implementations.
62. Can HashMap store null?
Yes.
HashMap supports:
- One null key
- Multiple null values
Not every Map implementation supports nulls. ConcurrentHashMap, for example, does not.
63. How does HashMap handle collisions?
A collision occurs when multiple keys map to the same bucket.
HashMap stores colliding entries together and compares keys to find the correct entry.
In modern Java implementations, heavily collided buckets can be transformed into tree-based structures when implementation-specific conditions are met, improving lookup behavior in extreme collision cases.
64. What is LinkedHashMap?
LinkedHashMap combines hash-based lookup with linked entry ordering.
It can maintain:
- Insertion order
- Access order when configured accordingly
Access-order mode is useful when implementing structures such as an LRU-style cache.
65. What is TreeMap?
TreeMap stores keys in sorted order using a red-black tree.
Ordering can come from:
- Natural ordering through Comparable
- A supplied Comparator
Its major operations typically have logarithmic-time characteristics.
66. HashMap vs TreeMap

| HashMap | TreeMap |
| Hash-based | Red-black tree based |
| No sorted-key guarantee | Keys remain sorted |
| Average basic lookup is typically constant-time | Basic operations are typically logarithmic |
| Supports one null key | Natural-order TreeMap does not support a null key in normal modern use |
| Requires good hashing | Requires ordering |
67. What is a Queue?
A Queue represents elements waiting for processing.
Typical operations include:
offer()
poll()
peek()
Many queues follow FIFO ordering, but implementations such as PriorityQueue use different rules.
68. What is Deque?
Deque stands for double-ended queue.
It supports insertion and removal from both ends:
addFirst()
addLast()
removeFirst()
removeLast()
ArrayDeque is frequently used for both queue and stack behavior.
69. Why is ArrayDeque preferred over Stack?
Stack is a legacy class derived from Vector.
For modern LIFO operations, ArrayDeque generally provides a cleaner API:
stack.push(value);
stack.pop();
stack.peek();
It also avoids the legacy synchronization design of Stack.
70. What is PriorityQueue?
PriorityQueue processes elements according to their priority rather than insertion order.
Priority is defined through:
- Natural ordering
- A custom Comparator
A common misconception is that iterating a PriorityQueue returns all values in completely sorted order. Its priority guarantee primarily concerns the head element.
71. What is Iterator?
Iterator provides sequential access to collection elements.
Its core methods are:
- hasNext()
- next()
- remove() where supported
It allows traversal without exposing the collection’s internal representation.
72. What is ListIterator?
ListIterator works specifically with lists and supports more capabilities than Iterator:
- Forward traversal
- Backward traversal
- Adding elements
- Replacing elements
- Retrieving index information
73. What is ConcurrentModificationException?
It may occur when a fail-fast iterator detects unsupported structural changes to a collection during iteration.
For example:
for (String name : names) {
names.remove(name);
}
can be unsafe.
Depending on the requirement, use iterator removal, removeIf(), or a suitable concurrent collection.
74. What is Comparable?
Comparable<T> defines a type’s natural ordering.
A class implements:
compareTo(T other)
For example, Employee might naturally order itself by employee ID.
75. What is Comparator?
Comparator<T> defines external or alternative ordering.
For example:
Comparator<Employee> bySalary =
Comparator.comparing(Employee::getSalary);
A class can therefore have multiple sorting strategies without changing its own natural ordering.
76. Comparable vs Comparator
| Comparable | Comparator |
| Defined by the class | Defined separately |
| Uses compareTo() | Uses compare() |
| Represents natural ordering | Represents custom ordering |
| Usually one natural strategy | Many comparator strategies can coexist |
77. What are generics?
Generics provide compile-time type safety while allowing reusable code.
Instead of:
List list = new ArrayList();
you can use:
List<String> names = new ArrayList<>();
This reduces explicit casting and helps detect type errors during compilation.
78. What is type erasure?
Java implements most generics using type erasure.
Generic type information is primarily enforced at compile time. During compilation, type parameters are erased or translated to their bounds, with casts inserted where required.
This explains why operations such as:
new T()
are generally not directly possible.
79. What is a bounded generic type?
A bounded type restricts which types may be used.
<T extends Number>
means T must be Number or a subtype.
This allows generic code to safely use operations available from the bound.
80. What are wildcards in generics?
Wildcards represent unknown types:
- List<?>
- List<? extends Number>
- List<? super Integer>
They are especially useful when writing APIs that need flexible generic relationships.
81. What does PECS mean?
PECS means:
Producer Extends, Consumer Super
The rule helps select wildcard bounds:
- Use ? extends T when the structure primarily produces T values.
- Use ? super T when it primarily consumes T values.
It is a guideline, not a replacement for understanding the actual type requirements.
82. What is an enum?
An enum represents a fixed set of named values.
enum Status {
NEW,
PROCESSING,
COMPLETED
}
Java enums can also contain fields, constructors, methods, and implemented interfaces.
83. What is an inner class?
An inner class is a non-static nested class.
It is associated with an instance of its outer class and can access outer-instance members.
84. What is a static nested class?
A static nested class belongs to the outer class rather than an outer object.
It does not automatically hold a reference to an outer-class instance.
85. What is an immutable class?
An immutable object cannot expose observable state changes after construction.
A typical immutable-class design uses:
- Private final fields
- No mutating methods
- Controlled inheritance
- Constructor validation
- Defensive copies of mutable inputs and outputs
String is a well-known immutable Java class.
Prepare for Core Java interviews with HCL GUVI’s Java Programming Course. Strengthen your Java fundamentals, OOP, JSP, Servlets, MySQL, design principles, and coding best practices through a structured beginner-to-expert curriculum and real-world projects.
Advanced Core Java Interview Questions
86. What is a lambda expression?

A lambda expression provides a concise implementation of a functional interface.
x -> x * x
For example:
List<Integer> values = List.of(1, 2, 3);
values.forEach(value -> System.out.println(value));
Lambdas are heavily used with Streams and functional APIs.
87. What is a functional interface?
A functional interface has exactly one abstract method.
Examples include:
- Predicate<T>: Tests a condition.
- Function<T,R>: Transforms a value.
- Consumer<T>: Consumes a value without returning one.
- Supplier<T>: Produces a value.
- Runnable: Represents work without a result.
It may still contain default, static, or inherited methods.
88. What does @FunctionalInterface do?
@FunctionalInterface documents that an interface is intended to remain functional.
It also lets the compiler report an error if more than one relevant abstract method is declared.
89. What is a method reference?
A method reference provides shorthand for a lambda that simply calls an existing method.
Examples include:
System.out::println
String::length
Integer::parseInt
Employee::new
Use it when it improves readability rather than mechanically replacing every lambda.
90. What is the Stream API?
The Stream API allows data-processing pipelines to be written declaratively.
A typical pipeline has three parts:
users.stream()
.filter(User::isActive)
.map(User::getEmail)
.toList();
Here:
- stream() creates the stream.
- filter() and map() are intermediate operations.
- toList() is a terminal operation.
91. Is Stream a collection?
No.
A collection stores data. A Stream represents a computation over a data source.
Streams are generally single-use. After a terminal operation consumes a Stream, it should not be reused.
92. What are intermediate Stream operations?
Intermediate operations return another Stream and are generally lazy.
Common examples include:
- filter()
- map()
- flatMap()
- distinct()
- sorted()
- limit()
- skip()
They normally begin processing only when a terminal operation is requested.
93. What are terminal operations?
Terminal operations trigger Stream processing and produce a result or side effect.
Examples include:
collect()
reduce()
count()
findFirst()
anyMatch()
forEach()
After a terminal operation executes, the Stream pipeline is consumed.
94. What is lazy evaluation in Streams?
Lazy evaluation means Stream intermediate operations are not normally executed immediately.
Consider:
Stream<String> stream =
names.stream()
.filter(name -> name.startsWith(“A”));
The filtering work begins only after a terminal operation such as:
stream.toList();
is requested.
95. What is map()?
map() transforms every stream element into another value.
List<Integer> lengths =
names.stream()
.map(String::length)
.toList();
The number of logical elements generally remains one output per input element.
96. What is flatMap()?
flatMap() is useful when one input can produce multiple nested values and you want one flattened Stream.
Suppose:
List<List<String>> skills;
You can flatten it using:
skills.stream()
.flatMap(List::stream)
.toList();
97. map() vs flatMap()
| map() | flatMap() |
| One input maps to one resulting element | One input can produce a nested stream of values |
| Preserves nested structures if mapping creates them | Flattens nested streams |
| Useful for direct transformations | Useful for collections inside collections or asynchronous composition concepts |
98. What is reduce()?
reduce() combines multiple Stream elements into a result.
For example:
int sum =
numbers.stream()
.reduce(0, Integer::sum);
The identity value is 0, and each element is combined into the accumulated result.
99. What is Optional?
Optional<T> represents either a present value or absence.
For example:
Optional<User> findUser(long id)
communicates that a user may not exist.
Useful operations include:
- map()
- flatMap()
- filter()
- orElse()
- orElseGet()
- orElseThrow()
100. orElse() vs orElseGet()
orElse() evaluates its alternative value immediately.
orElseGet() accepts a Supplier and evaluates the fallback lazily.
For expensive fallback creation, orElseGet() can therefore avoid unnecessary work.
101. Should Optional replace every null?
No.
Optional is especially useful when an API return value may legitimately be absent.
Using Optional indiscriminately for fields, setters, DTO properties, or every method parameter can complicate code without providing meaningful benefits.
102. What is multithreading?

Multithreading allows multiple threads to make progress within a process.
Threads share heap memory but maintain their own execution stacks.
This makes communication efficient but introduces challenges when several threads access mutable shared state.
103. How can tasks be executed concurrently in Java?
Common approaches include:
- Creating or starting Thread instances
- Implementing Runnable
- Implementing Callable
- Using ExecutorService
- Using CompletableFuture
- Using virtual threads for suitable workloads
Higher-level APIs are generally preferable to manually managing large numbers of platform threads.
104. Runnable vs Callable
| Runnable | Callable |
| run() | call() |
| No returned result | Returns a result |
| Cannot declare checked exceptions from its functional method | Can throw checked exceptions |
| Often used for simple tasks | Useful when computation returns a value |
105. What is ExecutorService?
ExecutorService manages task execution separately from task definition.
For example:
ExecutorService executor =
Executors.newFixedThreadPool(4);
executor.submit(task);
executor.shutdown();
It provides lifecycle management, task submission, and Future-based results.
106. Why use a thread pool?
Creating platform threads repeatedly can be expensive.
A thread pool:
- Reuses worker threads
- Limits platform-thread concurrency
- Reduces creation overhead
- Provides task queues
- Makes shutdown manageable
The correct pool size depends on workload characteristics.
107. What is synchronization?
Synchronization coordinates access to shared mutable state.
synchronized void increment() {
count++;
}
The intrinsic lock provides mutual exclusion and relevant memory-visibility guarantees.
108. Is synchronized reentrant?
Yes.
A thread that already owns an object’s intrinsic lock can enter another synchronized method or block requiring the same lock without deadlocking itself.
109. What is a race condition?
A race condition occurs when multiple threads manipulate shared state and correctness depends on execution timing.
For example:
count++;
is not one indivisible operation. It conceptually involves reading, modifying, and writing.
Concurrent executions can therefore lose updates.
110. What is deadlock?
Deadlock occurs when threads wait indefinitely for resources held by one another.
For example:
- Thread A owns Lock 1 and waits for Lock 2.
- Thread B owns Lock 2 and waits for Lock 1.
Neither can continue.
111. How can deadlock risk be reduced?
Useful strategies include:
- Consistent lock ordering: Acquire locks in the same order.
- Smaller critical sections: Hold locks only while necessary.
- Fewer nested locks: Reduce circular dependencies.
- Timed lock acquisition: Use APIs such as tryLock() where appropriate.
- Higher-level concurrency utilities: Prefer designs that reduce manual locking.
112. What does volatile do?
A volatile variable provides important visibility and ordering guarantees between threads.
volatile boolean running = true;
If one thread changes running, another thread reading it can observe the update according to Java’s volatile memory semantics.
However, volatile does not make compound operations such as count++ atomic.
113. volatile vs synchronized
| volatile | synchronized |
| Provides visibility and ordering guarantees for a variable | Provides locking plus visibility guarantees |
| Does not provide mutual exclusion | Provides mutual exclusion |
| Suitable for certain state flags | Suitable for protected critical sections |
| Cannot make compound updates atomic | Can protect compound operations |
114. What are atomic classes?
Classes from java.util.concurrent.atomic provide atomic operations without explicitly using synchronized blocks for certain use cases.
Examples include:
- AtomicInteger
- AtomicLong
- AtomicBoolean
- AtomicReference
For example:
counter.incrementAndGet();
performs an atomic increment.
115. AtomicLong vs LongAdder
AtomicLong maintains one atomic numeric value.
LongAdder distributes updates internally under contention and later combines them when read.
For high-contention counters where an immediately exact value is not required on every intermediate read, LongAdder may scale better.
116. What is ConcurrentHashMap?
ConcurrentHashMap is a thread-safe map designed for concurrent access.
Unlike synchronizing an entire HashMap for every operation, its internal concurrency design allows many operations to proceed efficiently at the same time.
117. Why does ConcurrentHashMap not allow null keys or values?
In concurrent code, null would make absence ambiguous.
If:
map.get(key)
returns null, the API needs to distinguish clearly between:
- No mapping exists
- A mapping exists whose value is null
Disallowing null removes this ambiguity.
118. What is CompletableFuture?
CompletableFuture supports asynchronous and composable computations.
For example:
CompletableFuture
.supplyAsync(this::loadUser)
.thenApply(this::formatUser)
.thenAccept(System.out::println);
It supports success pipelines, combinations, and exception handling.
119. thenApply() vs thenCompose()
Suppose an asynchronous function already returns another CompletableFuture.
thenApply() can produce:
CompletableFuture<CompletableFuture<Result>>
while thenCompose() flattens it to:
CompletableFuture<Result>
Conceptually, the relationship resembles map() versus flatMap().
120. What is the Fork/Join Framework?
The Fork/Join Framework supports divide-and-conquer parallelism.
A large task can be:
- Split into smaller tasks.
- Executed in parallel.
- Combined into one result.
It uses work-stealing so idle worker threads can take tasks from busy workers.
JVM, Memory, and Modern Java Interview Questions
121. What is heap memory?

The heap stores most dynamically allocated Java objects and arrays.
Heap memory is shared among threads and managed by the garbage collector.
A large heap does not automatically guarantee good performance. Object-retention patterns and garbage-collection behavior still matter.
122. What is stack memory?
Every thread has its own stack.
Each active method invocation typically creates a stack frame containing information such as:
- Local variables
- Operand stack state
- Method execution information
Deep or unbounded recursion can eventually produce StackOverflowError.
123. Heap vs Stack
| Heap | Stack |
| Stores most objects and arrays | Stores method execution frames |
| Shared by threads | Each thread has its own stack |
| Managed heavily by garbage collection | Frames are released as methods return |
| Large retention can lead to heap pressure | Deep recursion can exhaust stack space |
124. What is Metaspace?
Metaspace stores class metadata using native memory.
It replaced the older PermGen area starting with Java 8.
Applications that continuously load classes without releasing their class loaders can still consume excessive Metaspace.
125. What is garbage collection?
Garbage collection identifies objects that are no longer reachable through live references and reclaims their memory.
The broad process is automatic, but developers still need to design object lifetimes carefully.
Garbage collection does not mean memory management can be completely ignored.
126. Can Java applications have memory leaks?
Yes.
A Java memory leak occurs when objects are no longer useful but remain reachable, preventing garbage collection.
Common causes include:
- Unbounded caches
- Static collections
- Forgotten listeners
- Long-lived references
- ThreadLocal misuse
- Incorrect class-loader lifecycles
127. What is a strong reference?
A normal Java reference is a strong reference:
User user = new User();
As long as an object remains strongly reachable, it is generally not eligible for garbage collection.
128. What are weak references?
A WeakReference does not prevent an otherwise weakly reachable object from being garbage-collected.
Weak references can be useful for specialized caches, canonical mappings, or metadata structures where object retention should not be forced.
129. What is a class loader?
A class loader locates class definitions and makes them available to the JVM.
Common built-in loaders include:
- Bootstrap class loader
- Platform class loader
- Application class loader
Applications can also define custom class loaders.
130. What is parent delegation in class loading?
A class loader normally asks its parent to load a class before attempting to load the class itself.
This delegation helps:
- Protect core platform classes
- Prevent many duplicate definitions
- Maintain consistent class identities
Specialized frameworks may use different strategies where required.
131. What is JIT compilation?

JIT stands for Just-In-Time compilation.
The JVM initially works with bytecode and runtime profiling information. Frequently executed code can be compiled into optimized native machine instructions.
This is one reason long-running Java applications can become highly optimized during execution.
132. What is reflection?
Reflection allows code to inspect and interact with program structure at runtime.
It can inspect:
- Classes
- Methods
- Fields
- Constructors
- Annotations
Frameworks commonly use reflection for dependency injection, serialization, testing, and mapping.
133. What are the disadvantages of reflection?
Reflection is powerful but has trade-offs:
- Reduced compile-time safety
- More difficult refactoring
- More complex debugging
- Potential encapsulation concerns
- Runtime overhead in some use cases
It should be used deliberately rather than as a default design mechanism.
134. What are annotations?
Annotations attach metadata to program elements.
Examples include:
@Override
@Deprecated
@FunctionalInterface
Frameworks can inspect custom annotations at compile time or runtime depending on their retention policy.
135. What is a record?
A record provides concise syntax for classes primarily intended to carry data.
record User(long id, String name) {
}
Java automatically supplies important members such as accessors, equals(), hashCode(), and toString() based on the record components.
136. Are records deeply immutable?
No.
Record component fields are final, so their references cannot be reassigned after construction.
However:
record Order(List<String> items) {
}
can still hold a mutable List.
Use defensive copies if deep immutability is required.
137. What is a sealed class?
A sealed class or interface restricts which types may directly extend or implement it.
sealed interface Payment
permits CardPayment, CashPayment {
}
This is useful when the permitted hierarchy should be explicitly controlled.
138. What do sealed, final, and non-sealed mean?
Within a sealed hierarchy:
- final: Prevents further subclassing.
- sealed: Continues restricting permitted subclasses.
- non-sealed: Reopens the hierarchy for unrestricted subclassing.
This provides explicit control over how inheritance can continue.
139. What is pattern matching for instanceof?
Traditional code might look like:
if (obj instanceof String) {
String value = (String) obj;
}
Pattern matching allows:
if (obj instanceof String value) {
System.out.println(value.length());
}
The type test and variable binding happen together.
140. What is a switch expression?
A switch expression can directly return a value:
String label = switch (status) {
case NEW -> “New”;
case DONE -> “Completed”;
default -> “Unknown”;
};
Arrow-style cases also reduce accidental fall-through.
141. What is yield in a switch expression?
yield returns a value from a multi-statement switch-expression block.
int result = switch (type) {
case A -> 1;
case B -> {
int value = calculate();
yield value;
}
default -> 0;
};
142. What are text blocks?
Text blocks simplify multiline String literals.
For example:
String json = “””
{
“name”: “Java”,
“type”: “language”
}
“””;
They are useful for embedded JSON, SQL, XML, or HTML.
143. What is the Java Module System?

The Java Platform Module System organizes packages into explicit modules.
A module can declare:
- Which modules it requires
- Which packages it exports
- Which packages it opens
- Services it consumes or provides
This improves explicit dependency management and encapsulation for modular applications.
144. What is module-info.java?
module-info.java defines a module.
Example:
module com.example.app {
requires java.sql;
exports com.example.api;
}
It can use directives such as requires, exports, opens, uses, and provides.
145. What are virtual threads?
Virtual threads are lightweight Java threads managed primarily by the runtime rather than mapping one-to-one to operating-system threads.
They make thread-per-task programming practical for many high-concurrency, blocking workloads.
A simple example is:
Thread.startVirtualThread(() -> {
callRemoteService();
});
146. When are virtual threads useful?
Virtual threads are particularly useful when an application has many concurrent operations that spend significant time waiting.
Examples include:
- HTTP requests
- Database operations
- File I/O
- Network calls
- Other blocking operations
They do not automatically accelerate CPU-intensive algorithms.
147. Platform threads vs virtual threads
| Platform Threads | Virtual Threads |
| Typically map closely to OS threads | Scheduled by the Java runtime onto carrier threads |
| Relatively expensive in very large numbers | Much lighter-weight |
| Pools often limit thread count | Often created per task |
| Suitable for general thread execution | Especially useful for high-concurrency blocking workloads |
148. Should virtual threads be pooled?
Usually not simply to reduce thread-creation cost.
Virtual threads are intentionally lightweight and are often created for individual tasks.
Concurrency may still need to be limited based on scarce downstream resources such as database connections or external API limits.
149. What is thread pinning?
Pinning describes situations where a virtual thread cannot temporarily unmount from its carrier thread while executing certain operations.
The practical concern is that excessive pinning can reduce some scalability benefits expected from virtual threads.
Modern Java runtime improvements continue to reduce problematic pinning scenarios, but developers should still understand blocking and synchronization behavior.
150. Which modern Java features should candidates know in 2026?
Interview preparation should cover more than Java 8 lambdas and Streams.
Candidates should understand features such as:
- Modules: Explicit application modularity.
- Local variable type inference: var for local variables.
- Switch expressions: Cleaner value-producing switch logic.
- Text blocks: Multiline String literals.
- Records: Concise data carriers.
- Sealed classes: Controlled inheritance hierarchies.
- Pattern matching: Simplified type checking and extraction.
- Virtual threads: Scalable thread-per-task concurrency.
You should understand their use cases rather than memorizing release numbers alone.
Scenario-Based Core Java Interview Questions
151. You inserted an object into a HashMap but cannot retrieve it later. What would you check?
I would first inspect whether fields used in the key’s hashCode() or equals() implementation changed after insertion.
A mutable key can initially be placed in one bucket and later produce different hash information, making ordinary lookup fail.
Key insight: Prefer keys whose equality-relevant state remains immutable while they are stored in hash-based collections.
152. A HashMap suddenly becomes slow with a custom key class. What would you investigate?
I would check the following:
- Poor hashCode() distribution: Too many keys may be reaching the same buckets.
- Incorrect equals(): Equality logic may be expensive or inconsistent.
- Mutable keys: Key state may change after insertion.
- Excessive size: The map may be holding far more entries than expected.
- Memory pressure: GC or allocation behavior may be affecting observed performance.
I would profile before changing the data structure.
153. A HashSet contains what appear to be duplicate Employee objects. Why?
I would inspect Employee.equals() and Employee.hashCode().
If logical duplicates use Object’s default identity-based equality, HashSet considers two separately created instances different even if their fields look identical.
154. Two threads increment a shared counter 10,000 times each, but the final value is lower than 20,000. Why?
The likely issue is a race condition.
count++;
is not one atomic operation. Multiple threads can read the same old value before either writes the update.
Depending on the use case, I could use:
AtomicInteger
synchronization, or LongAdder.
155. Two application threads freeze while waiting for each other. How would you investigate it?
This suggests possible deadlock.
I would inspect thread dumps to determine:
- Which locks each thread owns.
- Which lock each thread is waiting for.
- Whether a circular dependency exists.
Then I would redesign lock ordering or reduce nested locking.
156. An ArrayList is being updated by multiple threads and behaves inconsistently. What is wrong?
ArrayList is not designed for unsynchronized concurrent structural modification.
Possible alternatives depend on the workload:
- External synchronization
- A concurrent collection
- CopyOnWriteArrayList for specific read-heavy use cases
- Eliminating shared mutable state
Choosing a thread-safe collection without understanding the access pattern can still produce poor performance.
157. Your code throws ConcurrentModificationException while removing items from a list. How would you fix it?
If removal needs to happen during iteration, I would use an operation designed for that purpose.
For example:
names.removeIf(String::isBlank);
or a supported iterator removal strategy.
Direct structural modification of a collection while using its fail-fast iterator can trigger ConcurrentModificationException.
158. A loop performs thousands of String concatenations. How would you improve it?
Instead of repeatedly doing:
result = result + value;
I would normally use StringBuilder:
StringBuilder result = new StringBuilder();
for (String value : values) {
result.append(value);
}
Repeated immutable concatenations can create unnecessary intermediate objects.
159. Your application runs out of heap even though Java has garbage collection. What would you do?
Garbage collection can reclaim only unreachable objects.
I would collect evidence such as:
- Heap usage
- Heap dump
- Dominator or retention analysis
- Cache size
- Static collections
- Listener registrations
- ThreadLocal values
If objects are still strongly reachable, increasing heap size may only delay the failure rather than fix it.
160. A recursive method produces StackOverflowError. What happened?
Each recursive method call adds another stack frame.
If recursion becomes too deep or never reaches its base condition, the thread can exhaust its stack.
I would verify the termination logic first and consider an iterative algorithm if recursion depth can grow unpredictably.
161. Your application has many blocking HTTP requests and platform threads are exhausted. What would you consider?
For modern Java, virtual threads would be worth evaluating.
They allow a large number of blocking tasks to use a thread-per-task style without requiring the same number of expensive operating-system threads.
I would still control external constraints such as API rate limits and connection pools.
162. Would you use virtual threads for a CPU-heavy image-processing task?
Not to make the computation itself faster.
CPU-bound work remains limited primarily by available processor resources.
Adding extremely high concurrency can create scheduling overhead without increasing computational capacity.
163. A parallel Stream is slower than a normal Stream. Why?
Parallel execution has overhead.
Possible reasons include:
- The dataset is too small.
- Each operation is too cheap.
- The source does not split efficiently.
- Tasks compete for shared resources.
- The workload is blocking.
- Combining partial results is expensive.
Parallel Streams should be measured rather than assumed to be faster.
164. A parallel Stream produces incorrect results while adding values to a shared ArrayList. Why?
The Stream is mutating shared non-thread-safe state.
Instead of:
List<Integer> result = new ArrayList<>();
values.parallelStream()
.forEach(result::add);
I would normally use an appropriate collector:
List<Integer> result =
values.parallelStream()
.toList();
Avoiding shared mutable state makes parallel processing safer.
165. Your Stream pipeline contains filter() and map(), but nothing happens. Why?
It may be missing a terminal operation.
This:
values.stream()
.filter(…)
.map(…);
only defines a lazy pipeline.
An operation such as:
toList()
count()
findFirst()
is required to trigger processing.
166. A production service has excellent average latency but occasional extreme pauses. What Java areas would you investigate?
I would avoid blaming garbage collection immediately.
I would examine:
- GC logs and pause behavior
- Heap allocation rate
- CPU saturation
- Thread contention
- Locking
- I/O latency
- External services
- JIT warmup
- Large object allocation
- Operating-system behavior
Performance diagnosis should be evidence-driven.
167. An application becomes slower after changing every collection operation to parallel Stream. Why?
Parallelism is not free.
I would compare workload size, operation cost, shared-state access, splitting efficiency, and use of the common ForkJoinPool.
Sequential Streams or ordinary loops can outperform parallel Streams for many everyday workloads.
168. A method returns null, and callers contain many defensive null checks. How might you redesign it?
First, I would determine what absence means in the domain.
Possible improvements include:
- Returning an empty collection
- Validating invariants earlier
- Using Optional for meaningful absent return values
- Using the Null Object pattern where appropriate
- Removing invalid states from the model
Optional should not be introduced mechanically without considering the API design.
169. You have two Employee sorting requirements: salary and joining date. Comparable or Comparator?
I would use separate Comparators.
For example:
Comparator<Employee> bySalary =
Comparator.comparing(Employee::getSalary);
Comparator<Employee> byJoiningDate =
Comparator.comparing(Employee::getJoiningDate);
Comparable is better reserved for a meaningful natural ordering.
170. Your application needs an immutable list. Is Collections.unmodifiableList() enough?
It depends.
Collections.unmodifiableList(original) creates an unmodifiable view, so changes to original may still be visible through that view.
For an independent unmodifiable copy, an approach such as:
List.copyOf(original)
may better match the requirement.
171. A record stores a mutable List. Can callers change the record’s apparent state?
Yes, if the same mutable List reference is exposed.
For stronger immutability:
record Order(List<String> items) {
Order {
items = List.copyOf(items);
}
}
This creates an unmodifiable copy during construction.
172. A synchronized method becomes a bottleneck. What would you do?
First, I would measure actual contention.
Then I might evaluate:
- Reducing the synchronized region
- Partitioning state
- Using atomic operations
- Using concurrent collections
- Using read/write locking where appropriate
- Redesigning around immutability
Removing synchronization without preserving correctness is not optimization.
173. Would ConcurrentHashMap make an entire multi-step business transaction thread-safe?
No.
For example:
if (!map.containsKey(key)) {
map.put(key, value);
}
contains multiple operations whose combined logic may require atomicity.
Use atomic map methods such as putIfAbsent() or computeIfAbsent() when they express the required operation, or coordinate the broader transaction separately.
174. Your validation code catches Exception everywhere. Why can that be problematic?
Catching an overly broad exception can:
- Hide unexpected programming errors
- Make failure behavior unclear
- Prevent useful failures from propagating
- Encourage generic error handling
- Make debugging harder
I would catch the exceptions that the layer can meaningfully handle or translate.
175. A catch block is empty. Why is that dangerous?
An empty catch block swallows the failure:
try {
process();
} catch (Exception e) {
}
The program may continue in an invalid state while losing the diagnostic cause.
An exception should normally be handled, translated, recorded appropriately, or allowed to propagate.
176. A file occasionally remains open after processing fails. What would you change?
I would use try-with-resources:
try (InputStream input =
Files.newInputStream(path)) {
process(input);
}
The runtime then closes the resource even if the processing code throws an exception.
177. You have 50 independent remote service calls. How might you execute them concurrently?
The choice depends on the application architecture.
Options may include:
- Virtual threads for blocking APIs
- CompletableFuture for asynchronous composition
- A controlled ExecutorService
- A reactive framework when the entire stack follows that model
I would also limit concurrency according to downstream service capacity.
178. A CompletableFuture pipeline produces nested futures. What should you change?
If this:
thenApply(…)
calls a function returning another CompletableFuture, I would normally use:
thenCompose(…)
to flatten the result.
This avoids ending with:
CompletableFuture<CompletableFuture<T>>
179. A method uses orElse(expensiveOperation()), but the expensive operation runs even when Optional contains a value. Why?
orElse() evaluates its argument eagerly.
I would use:
optional.orElseGet(this::expensiveOperation);
when fallback computation should happen only if the Optional is empty.
180. Your manager asks you to improve Java application performance immediately. Would you start rewriting code?
No.
I would first identify the actual bottleneck through measurement.
I would examine:
- CPU profiling.
- Allocation patterns.
- Garbage collection.
- Database calls.
- Network latency.
- Lock contention.
- Thread usage.
- I/O.
- Hot methods.
Key insight: Optimize measured bottlenecks rather than code that merely looks inefficient.
How to Prepare for a Core Java Interview
A strong Core Java interview preparation strategy should combine concepts with coding, debugging, and explanation practice.
Do not stop after memorizing definitions. Be prepared to explain why one Java feature is preferable to another in a specific situation.
Your preparation should include:
- Fundamentals: Understand JDK, JVM, bytecode, objects, methods, and data types.
- OOP: Practise inheritance, overriding, abstraction, interfaces, and composition.
- Collections: Know when to choose ArrayList, HashSet, HashMap, TreeMap, Queue, or concurrent collections.
- Equality: Be able to explain ==, equals(), and hashCode() without notes.
- Exceptions: Know how to propagate, translate, and clean up after failures.
- Streams: Practise filter, map, flatMap, reduce, collectors, and Optional.
- Concurrency: Understand race conditions, deadlocks, synchronization, atomics, executors, and virtual threads.
- JVM: Review heap, stack, garbage collection, JIT compilation, and memory leaks.
- Modern Java: Prepare records, sealed classes, pattern matching, switch expressions, modules, and virtual threads.
- Real Projects: Be able to explain why you selected particular Java APIs in your previous applications.
What Core Java Topics Should Freshers Prioritize?
Freshers do not need to begin with complicated JVM tuning. They should first build strong fundamentals.
The highest-priority areas are:
- JDK, JRE, and JVM
- Variables and data types
- Classes and objects
- Constructors
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
- Interfaces
- Strings
- Exception handling
- Collections
- equals() and hashCode()
- Generics
- Basic Streams
- Basic multithreading
Once these are comfortable, move into concurrency utilities and JVM internals.
What Should Experienced Java Developers Prepare Differently?
Experienced candidates are more likely to be tested on decisions, trade-offs, and production behavior.
They should be prepared to discuss:
- HashMap internals and collision behavior
- Immutable object design
- Collection selection
- Generics and API design
- Stream performance
- Synchronization and the Java Memory Model
- Executor configuration
- CompletableFuture
- Race conditions and deadlocks
- ConcurrentHashMap
- JVM memory
- Garbage collection
- Memory leaks
- Thread dumps
- Performance profiling
- Virtual threads
- Records and sealed hierarchies
- Production troubleshooting
Interviewers may also ask you to describe a real bug you diagnosed and why your solution worked.
What Do Interviewers Look for in Core Java Candidates?
Strong candidates do more than state definitions. They connect Java concepts to real program behavior.
Interviewers generally look for the ability to:
- Select suitable Java collections
- Explain OOP without textbook-only definitions
- Implement correct equality
- Handle exceptions appropriately
- Recognize unsafe shared state
- Explain thread-safety trade-offs
- Read and reason about Java code
- Understand memory behavior
- Diagnose performance problems
- Explain modern Java features in practical terms
- Is Core Java enough for a Java developer interview?
Core Java is usually the foundation. Backend roles may additionally test SQL, Spring, REST APIs, databases, design patterns, microservices, testing, or system design depending on experience level.
- Are Collections important for Java interviews?
Yes. Collections test several concepts simultaneously, including generics, equality, hashing, ordering, complexity, mutability, and concurrency.
- Is HashMap still an important interview topic in 2026?
Yes. HashMap questions reveal whether candidates understand hashCode(), equals(), collisions, mutable keys, complexity, and collection design rather than just API syntax.
- Do Java interviews still ask Java 8 questions?
Yes. Lambdas, Streams, Optional, functional interfaces, and method references remain fundamental Java concepts. Modern Java knowledge should build on these rather than replace them.
- Should I prepare virtual threads for Java interviews?
Yes, particularly for backend and experienced Java roles. Candidates should understand that virtual threads primarily improve scalability for many blocking tasks rather than making CPU-bound code inherently faster.
How Should You Answer Scenario-Based Java Interview Questions?
Do not jump immediately to an API name. A stronger answer follows a diagnostic sequence:
- Identify the symptom: Determine whether the issue involves correctness, memory, concurrency, latency, or design.
- Find evidence: Use stack traces, logs, thread dumps, heap analysis, metrics, or profiling.
- Explain the mechanism: Describe why Java behaves that way.
- Choose a solution: Recommend the appropriate API or design change.
- Discuss trade-offs: Consider complexity, memory, latency, throughput, and maintainability.
- Validate the fix: Explain how you would confirm that the problem has actually been solved.
Conclusion
Core Java interviews in 2026 require a combination of strong fundamentals and practical reasoning. Beginners should understand classes, objects, OOP, constructors, Strings, exceptions, and collections. Intermediate candidates need stronger knowledge of generics, functional programming, Streams, Optional, and multithreading.
Experienced developers should go deeper into HashMap internals, concurrency, synchronization, ExecutorService, CompletableFuture, JVM memory, garbage collection, performance profiling, records, sealed classes, pattern matching, and virtual threads.
Use these Core Java interview questions and answers progressively. Start with concepts you can explain confidently, then practise comparisons, coding questions, and real-world scenarios.
The strongest interview answer does not simply state what a Java feature is. It explains how it works, why it matters, when it should be used, and what trade-offs it introduces.
FAQs
1. How should I prepare for a Core Java interview in 2026?
Start with OOP, Strings, exceptions, collections, generics, and Java 8 features. Then move into Streams, multithreading, JVM internals, garbage collection, concurrent collections, and modern Java features. Practise coding and scenario questions alongside theory.
2. What is the best trick for answering Core Java interview questions?
Use a three-part answer: define the concept directly, explain how it works, and give one realistic use case or comparison. For debugging questions, explain how you would confirm the problem before suggesting a fix.
3. What mistakes should I avoid in a Java interview?
Avoid saying Java is pass-by-reference, assuming HashMap is thread-safe, confusing == with equals(), treating volatile as a replacement for synchronization, or claiming parallel Streams and virtual threads always improve performance.
4. How can freshers perform better in Java interviews?
Focus on strong fundamentals and write small programs regularly. Practise OOP, Strings, collections, exceptions, equals() and hashCode(), and basic multithreading. If you do not know an advanced answer, explain the part you understand instead of guessing.
5. How should experienced developers prepare for Java scenario questions?
Review real production situations involving performance, memory, concurrency, API design, exceptions, and debugging. Be ready to explain what evidence you would collect, why the problem occurs, which solution you would choose, and what trade-offs that solution introduces.



its really helpfull for an placement practice thank u sir collective content with effective learning u have given here .enjoyed without any confusion on core java . bcs u had teach us .