Interview · 1497 words · 8 minute read
Top 50 Java Interview Questions for 2026 (with Answers)
By Priyanshu Rauth · Published 2026-02-10 · Updated 2026-08-24
This is a study set, not a claim about the exact questions any employer will ask. A strong answer gives the rule, one consequence, and a small example or trade-off. Use the questions to find gaps, then verify behavior in the Java compiler and practice the linked topic.
Language and object model (1-15)
- What are JDK, JVM, and JRE? The JDK contains development tools such as javac plus a runtime. The JVM executes bytecode. “JRE” commonly means the runtime components needed to run Java applications, though modern JDK distributions and modular runtime images have changed how a separate JRE is packaged.
- Why can Java bytecode run on different operating systems? javac targets a JVM class-file format. A compatible JVM implementation handles the operating-system and processor details.
- Primitive versus reference type? A primitive variable contains a primitive value. A reference variable contains a reference to an object or null. Assignment copies whichever value the variable contains.
- What does pass-by-value mean in Java? Every argument is copied. For an object argument, the copied value is the reference, so a method can mutate the same object but cannot replace the caller’s variable.
==versusequals? For references,==compares identity.equalsexpresses logical equality when the class overrides it. For primitives,==compares values.- Why are Strings immutable? A String’s character sequence cannot change after construction. Operations return new strings, enabling safe sharing and stable value/hash behavior.
- String, StringBuilder, or StringBuffer? Use String for immutable text, StringBuilder for repeated mutation within ordinary single-threaded work, and StringBuffer only when its synchronized operations match a real shared-mutation requirement.
- Overloading versus overriding? Overloading selects among same-name parameter lists at compile time. Overriding supplies subtype behavior for the same instance-method signature and dispatches at runtime.
- What does
staticmean? A static member belongs to the class rather than one instance. Static methods have nothisreference and cannot directly access instance state. - What does
finalmean? A final variable cannot be reassigned, a final method cannot be overridden, and a final class cannot be extended. A final reference may still point to a mutable object. - Is Java multiple-inheritance capable? A class extends one class but can implement multiple interfaces. Interface default-method conflicts must be resolved explicitly.
- Abstract class versus interface? An abstract class can hold instance state and constructors and suits a close family with shared implementation. An interface describes a contract that otherwise unrelated types can implement.
- What is encapsulation? It is keeping representation and state transitions behind a controlled API so callers cannot violate the object’s rules.
- What is polymorphism? Code uses a parent or interface contract while the runtime selects the implementation belonging to the actual object.
- Composition versus inheritance? Composition delegates to contained collaborators and keeps relationships flexible. Inheritance should represent a genuine substitutable subtype.
Collections and generics (16-28)
- List versus Set? A List is ordered and permits duplicates; a Set models unique elements. The implementation determines additional ordering guarantees.
- ArrayList versus LinkedList? ArrayList provides fast indexed access and compact iteration. LinkedList has node overhead and linear indexed access; even insertions require finding the position. Choose from measured access patterns, not the phrase “fast insertion.”
- HashMap ordering? HashMap promises no iteration order. Use LinkedHashMap for encounter order or TreeMap for key-sorted order.
- How does a hash collection find a key? It uses hashCode to choose a region and equals to identify a logically equal key among candidates. Correct keys need compatible, stable equals and hashCode implementations.
- Why must equal objects have equal hash codes? A hash collection may search only the region selected by the hash. Different hashes for equal objects can make lookup fail.
- Comparable versus Comparator? Comparable defines a type’s natural ordering. Comparator is an external ordering strategy and allows several orderings for the same type.
- What are generics for? They express type relationships and move many invalid element operations to compile time without requiring manual casts.
- What is type erasure? Most generic type parameters are not reified in runtime objects. The compiler checks and translates generic code, which is why operations such as
new T()are generally unavailable. ? extends Tversus? super T? An extends-bounded source can safely produce T values but generally cannot accept them. A super-bounded destination can accept T values. “Producer extends, consumer super” is the memory aid.- Why prefer ArrayDeque to Stack? ArrayDeque implements efficient stack and queue operations without the legacy Vector inheritance and API of Stack. It does not permit null elements.
- What causes ConcurrentModificationException? Many fail-fast iterators detect unsupported structural modification outside the iterator. It is a bug signal, not a thread-safety guarantee.
- Unmodifiable versus immutable collection? An unmodifiable view blocks changes through that reference but may reflect changes to its backing collection. An immutable value has no observable mutation path.
- When use a PriorityQueue? Use it when repeated access to the least or greatest element by a comparator matters. Iterating it does not produce globally sorted order.
Exceptions, resources, and APIs (29-37)
- Checked versus unchecked exception? Checked exceptions are subject to catch-or-declare rules. RuntimeException subclasses are unchecked. API contract and recoverability should guide handling.
- What should a catch block do? Recover, add useful context, translate at an abstraction boundary, or report at the boundary. An empty catch block hides the failure.
- What is try-with-resources? It closes declared AutoCloseable resources in reverse order, including when the body throws. Close failures can be attached as suppressed exceptions.
- Does finally always run? It normally runs as control leaves try/catch, but abrupt process or JVM termination can prevent it. Returning from finally is dangerous because it can mask another result.
throwversusthrows?throwraises one exception value. Athrowsclause declares checked failures a method may propagate.- What is exception chaining? A higher-level exception retains the original as its cause, preserving diagnostic context while presenting an appropriate API abstraction.
- Why validate constructor arguments? Rejecting invalid input prevents creation of an object whose invariant is already broken.
- What is Optional for? Optional can represent a possibly absent return value. It is not a universal replacement for fields, parameters, collections, or input validation.
- What is a record? A record is a concise class for transparent data carriers. The compiler supplies component accessors and value-based equals, hashCode, and toString; validation can be added in a compact constructor.
Concurrency and JVM (38-47)
- Process versus thread? A process has its own runtime resources; threads within a process share heap state while keeping their own call stacks.
- What is a race condition? The result depends on an uncontrolled ordering of operations between threads, often because a compound read-modify-write is not atomic.
- What does synchronized provide? Locking on the same monitor provides mutual exclusion and establishes visibility relationships for actions before unlock and after a later lock.
- What does volatile provide? Reads observe suitably ordered writes to that variable, but volatile does not make compound operations such as increment atomic.
- Deadlock? Threads wait indefinitely for resources held in a cycle. Consistent lock ordering and smaller critical sections reduce the risk.
- ExecutorService? It separates task submission from thread management. Shut it down deliberately and handle task failures through Future or the task boundary.
- What is CompletableFuture? It represents a result that may complete later and supports dependent asynchronous stages. Choose the executor and error path explicitly.
- Stack versus heap? Each thread has stack frames for calls and local execution state; objects are generally allocated on the managed heap, subject to JVM optimization.
- What does garbage collection guarantee? It reclaims unreachable managed objects eventually according to collector behavior; it does not guarantee prompt release of files, sockets, or other external resources.
- What is class loading? Class loaders locate class definitions; the JVM links and initializes classes as required. Class identity includes both class name and defining loader.
Practical coding (48-50)
- How do you design a testable method? Pass dependencies and input explicitly, return a result, isolate I/O, and cover boundaries rather than relying on printed output inspection.
- How do you diagnose a slow solution? Define input size, identify nested or repeated work, estimate complexity, measure representative inputs, and optimize the actual bottleneck while preserving tests.
- What should you do when you do not know an answer? State what you know, identify the uncertain part, reason from a small example, and explain how you would verify it. Invented certainty is worse than a bounded gap.
Tested dispatch example
public class Main {
interface Message { String text(); }
record Greeting(String name) implements Message {
public String text() { return "Hello, " + name; }
}
static void print(Message message) { System.out.println(message.text()); }
public static void main(String[] args) { print(new Greeting("Java")); }
}
The output is Hello, Java. The example combines an interface contract, a record, overriding, and dispatch through an interface reference.
How to practice the list
Answer five questions aloud, then write a tiny counterexample for any answer that felt vague. Use OOP practice, collections exercises, and exception exercises rather than memorizing definitions. Common mistakes are absolute claims (“finally always runs”), complexity without a defined input, and reciting implementation trivia without explaining when it affects code.
Continue with the Java practice path · Try code in the Java compiler