Java Interview Questions and Answers: 2027 Edition With Code
java-interview-questions is a free list of Java interview questions with answers and tested code, for junior, mid-level and senior Java developers. It covers core Java and OOP, String and immutability, equals/hashCode, the Collections Framework and HashMap internals, generics, exceptions, Java 8+ streams and lambdas, modern Java (records, sealed classes, pattern matching, virtual threads), concurrency, the JVM, garbage collection and memory, plus Spring Boot, JPA and testing questions that come up in backend interviews. The coding answers (LRU cache, producer-consumer, singletons, stream puzzles, odd/even threads) are in src/main/java/interview and tested without any build tool.
Last reviewed: December 2026. Version notes refer to Java 21 and Java 25 (the current long-term support releases from most vendors), Java 27 (released September 15, 2026), and Java 26. Features marked “preview” need
--enable-previewand can change.
git clone https://github.com/Ralpberry-Labs/java-interview-questions
cd java-interview-questions
./run-tests.sh # javac + java only, needs JDK 21 or newer
Table of Contents
- How to Use This List
- A 4-Week Preparation Plan
- Java Versions You Should Know
- 1. Core Java Basics
- 2. Object-Oriented Programming
- 3. Strings and Immutability
- 4. equals, hashCode and Object Methods
- 5. Collections Framework
- 6. Generics
- 7. Exceptions
- 8. Lambdas, Functional Interfaces and Streams
- 9. Modern Java: Records, Sealed Types, Pattern Matching
- 10. Concurrency and Multithreading
- 11. Virtual Threads and Structured Concurrency
- 12. JVM, Memory and Garbage Collection
- 13. Design Patterns in Java
- 14. Spring Boot, JPA and Testing
- 15. Coding Round
- 16. Output and Trick Questions
- Best Resources to Prepare
- FAQ
- Where to Go Next
- Contributing
- License
How to Use This List
- Levels: [J] junior (0 to 2 years), [M] mid-level, [S] senior. Senior interviews still include junior questions; the expected answer is deeper.
- Answer out loud before reading. Interviewers listen for reasoning and correct vocabulary.
- For coding questions, open the linked file, delete the method body, rewrite it, and run
./run-tests.sh.
A 4-Week Preparation Plan
| Week | Topics | Practice | Done when you can… |
|---|---|---|---|
| 1 | Sections 1 to 4: basics, OOP, strings, equals/hashCode |
10 easy LeetCode problems in Java | Explain why String is immutable and the equals/hashCode contract with an example |
| 2 | Sections 5 to 8: collections, generics, exceptions, streams | Rewrite loops as streams; Streams.java |
Describe how HashMap handles collisions and resizing; write groupingBy queries from memory |
| 3 | Sections 9 to 12: modern Java, concurrency, JVM, GC | BoundedBuffer, Concurrency |
Explain volatile, synchronized, happens-before, virtual threads, and how G1 works at a high level |
| 4 | Sections 13 to 16 + mock interviews | LRU cache, producer-consumer, 15 medium LeetCode problems | Finish a 45-minute mock with working, tested code |
Java Versions You Should Know
| Version | Released | Status in December 2026 | Features interviewers ask about |
|---|---|---|---|
| Java 8 | 2014 | Old LTS, still in legacy systems | Lambdas, streams, Optional, java.time, default methods |
| Java 11 | 2018 | LTS | var in lambdas, HttpClient, String methods (isBlank, lines, strip), single-file java Hello.java |
| Java 17 | 2021 | LTS | Records, sealed classes, text blocks, pattern matching for instanceof, switch expressions |
| Java 21 | September 2023 | LTS | Virtual threads (JEP 444), pattern matching for switch (JEP 441), record patterns (JEP 440), sequenced collections (JEP 431), generational ZGC |
| Java 25 | September 2025 | Current LTS | Scoped values (JEP 506), module import declarations (JEP 511), compact source files and instance main (JEP 512), flexible constructor bodies (JEP 513), compact object headers (JEP 519) |
| Java 26 | March 2026 | Feature release | HTTP/3 for the HTTP Client (JEP 517), Applet API removed (JEP 504), warnings for mutating final fields via deep reflection (JEP 500) |
| Java 27 | September 15, 2026 | Latest feature release | G1 as default GC in all environments (JEP 523), compact object headers by default (JEP 534), post-quantum hybrid key exchange for TLS 1.3 (JEP 527) |
Between 21 and 25, Java 22 finalized the Foreign Function & Memory API (JEP 454) and unnamed variables _ (JEP 456), and Java 24 finalized Stream Gatherers (JEP 485) and removed virtual-thread pinning on synchronized (JEP 491). Structured concurrency is still a preview feature in Java 27. The official lists are on the OpenJDK pages for JDK 21, JDK 25 and JDK 27.
Which version should you study? Learn Java 17 and 21 features thoroughly, since most production code runs on 17, 21 or 25. Mention Java 25 features to show you keep up.
1. Core Java Basics
Q1. What are the JDK, JRE and JVM? [J]
- JVM (Java Virtual Machine): runs bytecode. It loads classes, verifies them, interprets them, compiles hot code to machine code with the JIT compiler, and manages memory with a garbage collector.
- JRE (runtime environment): the JVM plus the standard class library, enough to run programs. Since Java 11, vendors no longer ship a separate JRE by default; you use the JDK or build a trimmed runtime with
jlink. - JDK (development kit): the JRE plus tools like
javac,jar,jshell,jlink,jcmdandjfr.
Q2. Why is Java “write once, run anywhere”? [J]
javac compiles source to platform-neutral bytecode (.class files). Any JVM on any OS and CPU can run that bytecode. The JVM itself is platform-specific; your program is not (unless it uses native code via JNI or the Foreign Function & Memory API).
Q3. What are the primitive types? [J]
byte (8-bit), short (16), int (32), long (64), float (32-bit IEEE 754), double (64), char (16-bit UTF-16 code unit), boolean. Each has a wrapper class (Integer, Long…). Primitives live directly in variables and arrays; wrappers are objects, can be null, and are needed for generics (List<Integer>).
Q4. What is autoboxing, and what can go wrong? [J]
The compiler converts between primitives and wrappers automatically: List<Integer> list; list.add(5) boxes 5. Pitfalls:
NullPointerExceptionon unboxing:Integer x = null; int y = x;throws.==on wrappers compares references:Integer a = 127, b = 127; a == bistruebecause values from -128 to 127 are cached, but with1000it is usuallyfalse. Useequals.- Performance: boxing in tight loops creates garbage. Use
IntStream, primitive arrays, or specialized collections.
Q5. Is Java pass-by-value or pass-by-reference? [J]
Always pass-by-value. For objects, the value passed is a copy of the reference. A method can change the object the reference points to (list.add(x) is visible to the caller), but re-assigning the parameter (list = new ArrayList<>()) does not affect the caller’s variable.
Q6. What do static and final mean? [J]
staticfield or method: belongs to the class, not to an instance.staticnested class: does not hold a reference to an outer instance.staticblock: runs once when the class is initialized.finalvariable: assigned once.finalmethod: cannot be overridden.finalclass: cannot be extended (String,Integer). Afinalreference to a mutable object does not make the object immutable.
Q7. What is var? [J]
Local variable type inference (Java 10): var list = new ArrayList<String>();. The type is still static and fixed at compile time; var only saves typing. It works for local variables, for loops and lambda parameters, not for fields, method parameters or return types. Avoid it when the type is not obvious from the right-hand side.
Q8. What is the difference between == and equals()? [J]
== compares primitive values or, for objects, whether two references point to the same object. equals() compares logical equality as defined by the class. String, wrappers, collections and records override equals to compare contents. Object.equals (the default) is the same as ==.
Q9. What are the access modifiers? [J]
| Modifier | Same class | Same package | Subclass (other package) | Everywhere |
|---|---|---|---|---|
private |
Yes | No | No | No |
| (none, package-private) | Yes | Yes | No | No |
protected |
Yes | Yes | Yes | No |
public |
Yes | Yes | Yes | Yes |
With the module system (Java 9+), a public class is only visible outside its module if its package is exportsed in module-info.java.
Q10. What is the main method, and what changed in Java 25? [J]
Classically, public static void main(String[] args) in a class. Java 25 finalized compact source files and instance main methods (JEP 512): a source file can contain just void main() { IO.println("Hello"); } with no class declaration and no static, which is meant for beginners and small scripts. Run it directly with java Hello.java.
2. Object-Oriented Programming
Q11. What are the four pillars of OOP? [J]
- Encapsulation: hide state behind methods (
privatefields, validated setters or no setters). - Abstraction: expose what an object does, hide how (interfaces, abstract classes).
- Inheritance: a class reuses and specializes another (
extends). - Polymorphism: one interface, many implementations; the method that runs is chosen at runtime by the object’s actual class (dynamic dispatch).
Give a concrete example for each in interviews, such as a PaymentMethod interface with Card and BankTransfer implementations.
Q12. Abstract class vs interface? [J]
| Abstract class | Interface | |
|---|---|---|
| Multiple inheritance | One superclass only | A class can implement many |
| State | Instance fields allowed | Only static final constants |
| Constructors | Yes | No |
| Methods | Abstract and concrete | Abstract, default, static, private (Java 9+) |
| Use when | Sharing state and code among closely related classes | Defining a capability or contract (Comparable, Runnable) |
Since Java 8 default methods blur the line, but interfaces still cannot hold instance state.
Q13. Overloading vs overriding? [J]
Overloading: same method name, different parameter lists, in the same class; resolved at compile time from the static types of the arguments. Overriding: a subclass provides a new implementation of an inherited method with the same signature; resolved at runtime from the object’s actual class. Overriding rules: same or covariant return type, no weaker access, no new or broader checked exceptions. Always use @Override so the compiler catches mistakes.
Q14. Composition vs inheritance? [M]
Inheritance creates a tight “is-a” coupling: subclasses depend on superclass internals, and a change in the parent can break children (the “fragile base class” problem). Composition (“has-a”) holds other objects as fields and delegates to them, which is more flexible and easier to test. The standard advice is to favor composition and use inheritance only for true “is-a” relationships designed for extension.
Q15. What is the Liskov Substitution Principle? [M]
A subclass must work anywhere its superclass is expected without breaking correctness. The classic violation: Square extends Rectangle, where setting the width of a square also changes its height, so code that sets width and height independently breaks. LSP is the “L” in SOLID (Single responsibility, Open/closed, Liskov substitution, Interface segregation, Dependency inversion). Expect to explain all five with examples.
Q16. Can you override a static or private method? [J]
No. Static methods are hidden, not overridden: the version called depends on the reference’s compile-time type. Private methods are not visible to subclasses, so a method with the same name in the subclass is a new, unrelated method.
Q17. What are the kinds of nested classes? [M]
- Static nested class: no reference to an outer instance. Use by default.
- Inner class (non-static): holds a hidden reference to the outer instance, which can cause memory leaks if the inner object outlives the outer one.
- Local class: declared inside a method.
- Anonymous class: an unnamed one-off implementation, mostly replaced by lambdas for functional interfaces.
Q18. What is the order of initialization when you create an object? [M]
- Class initialization (once): static fields and static blocks, in source order, superclass first.
- For each
new: the superclass constructor runs first (via the implicit or explicitsuper(...)), then instance field initializers and instance blocks in source order, then the rest of the constructor body.
Java 25’s flexible constructor bodies (JEP 513) allow statements before super(...), as long as they do not use the object being constructed, so you can validate arguments before calling the superclass constructor.
3. Strings and Immutability
Q19. Why is String immutable? [J]
- Security: strings are used for class names, file paths, URLs and credentials; they cannot be changed after validation.
- String pool: sharing literals is only safe if they cannot change.
- Thread safety: immutable objects can be shared freely.
- Hash caching:
Stringcaches itshashCode, which makes it a fastHashMapkey.
Q20. What is the string pool? What does intern() do? [M]
String literals are stored in a pool on the heap, and identical literals share one object. new String("hi") always creates a new object. s.intern() returns the pooled instance with the same contents. That is why "hi" == "hi" is true but new String("hi") == "hi" is false. Always compare strings with equals.
Q21. String vs StringBuilder vs StringBuffer? [J]
String is immutable; each change creates a new object. StringBuilder is a mutable buffer, not synchronized, and the right choice for building strings in loops. StringBuffer is the older synchronized version; it is rarely needed. A single expression like "a" + b + "c" is fine; the compiler optimizes it (since Java 9 via invokedynamic and StringConcatFactory).
Q22. How do you make a class immutable? [M]
- Make the class
final(or use a private constructor with factories) so subclasses cannot add mutability. - Make all fields
private final. - Do not provide setters.
- Defensively copy mutable inputs in the constructor and mutable outputs in getters (
List.copyOf(list)). - Return new objects from “modifying” methods.
Money.java is an example. A record with immutable component types does most of this for you.
Q23. What are text blocks? [J]
Java 15’s multi-line string literals, delimited by """. Incidental indentation is stripped, and you do not need to escape quotes. Useful for SQL, JSON and HTML in code and tests.
4. equals, hashCode and Object Methods
Q24. What is the equals and hashCode contract? [J]
- If
a.equals(b), thena.hashCode() == b.hashCode()must be true. - If hash codes are equal, the objects may or may not be equal (collisions are allowed).
equalsmust be reflexive, symmetric, transitive, consistent, and returnfalsefornull.
If you override equals but not hashCode, equal objects land in different HashMap buckets, so map.get(equalKey) returns null and a HashSet keeps duplicates. The test in AllTests.java checks that a HashSet deduplicates two equal Money objects.
Q25. What happens if a HashMap key is mutated after insertion? [M]
If the fields used by hashCode change, the entry sits in the bucket for the old hash. Lookups compute the new hash, search the wrong bucket, and fail; the entry is effectively lost but still uses memory. Use immutable keys (String, records with immutable fields).
Q26. What methods does Object have? [J]
equals, hashCode, toString, getClass, clone (protected), finalize (deprecated for removal), and wait/notify/notifyAll for monitors. Know why clone is considered broken (shallow by default, needs Cloneable, bypasses constructors) and that copy constructors or static factories are preferred.
Q27. Comparable vs Comparator? [J]
Comparable<T> defines a class’s natural order with compareTo (e.g. String, Integer). Comparator<T> is an external ordering you pass in, and you can have many: Comparator.comparing(Employee::dept).thenComparing(Employee::salary, Comparator.reverseOrder()). Keep compareTo consistent with equals, or sorted collections like TreeSet will behave surprisingly.
5. Collections Framework
Q28. Describe the main collection interfaces. [J]
| Interface | Ordered | Duplicates | Common implementations |
|---|---|---|---|
List |
Yes, by index | Yes | ArrayList, LinkedList |
Set |
Depends | No | HashSet, LinkedHashSet, TreeSet |
Queue / Deque |
FIFO / both ends | Yes | ArrayDeque, PriorityQueue, LinkedList |
Map (not a Collection) |
Depends | Unique keys | HashMap, LinkedHashMap, TreeMap, ConcurrentHashMap |
Java 21 added sequenced collections (JEP 431): SequencedCollection, SequencedSet and SequencedMap with getFirst(), getLast(), addFirst(), reversed() and similar methods on lists, deques, LinkedHashSet, LinkedHashMap and sorted collections.
Q29. ArrayList vs LinkedList? [J]
| Operation | ArrayList |
LinkedList |
|---|---|---|
get(i) |
O(1) | O(n) |
| Add at end | Amortized O(1) | O(1) |
| Insert/remove in middle | O(n) shifting | O(1) once you have the node, O(n) to find it |
| Memory | Compact array | One node object per element with two pointers |
ArrayList wins in nearly all real workloads thanks to CPU cache locality. For a queue or stack use ArrayDeque, not LinkedList or the legacy Stack.
Q30. How does HashMap work internally? [M]
- An array of buckets (default capacity 16, always a power of two).
put(k, v): computek.hashCode(), spread the high bits (h ^ (h >>> 16)), and pick a bucket withhash & (capacity - 1).- Collisions are stored as a linked list in the bucket. When a bucket grows past 8 entries (and the table has at least 64 buckets), it becomes a red-black tree, so the worst case drops from O(n) to O(log n). This was added in Java 8.
- When size exceeds
capacity × loadFactor(default 0.75), the table doubles and entries are redistributed. - One
nullkey is allowed (stored in bucket 0).HashMapis not thread-safe.
Average get/put is O(1). Good hashCode distribution matters.
Q31. HashMap vs LinkedHashMap vs TreeMap? [J]
HashMap: no order, O(1) average. LinkedHashMap: keeps insertion order (or access order with the accessOrder constructor flag, which makes a quick LRU cache with removeEldestEntry). TreeMap: sorted by key, O(log n), supports range queries (headMap, ceilingKey, floorEntry).
Q32. HashMap vs Hashtable vs ConcurrentHashMap? [M]
Hashtable is legacy: every method is synchronized (one lock for everything) and it allows no nulls. Collections.synchronizedMap has the same single-lock design. ConcurrentHashMap allows concurrent reads without locking and locks individual bins for writes using CAS operations, so it scales with threads. It forbids null keys and values (so get returning null always means “absent”), and offers atomic compound operations: computeIfAbsent, merge, compute.
counts.merge(word, 1, Integer::sum); // atomic increment in a ConcurrentHashMap
Q33. What is a fail-fast iterator? [M]
Most collection iterators track a modification count. If the collection is structurally modified during iteration by anything other than the iterator’s own remove, the next call throws ConcurrentModificationException. To remove while iterating, use iterator.remove() or list.removeIf(predicate). Concurrent collections (ConcurrentHashMap, CopyOnWriteArrayList) have weakly consistent iterators that never throw this exception.
Q34. List.of vs Arrays.asList vs Collections.unmodifiableList? [M]
List.of(...)(Java 9): truly immutable, rejectsnullelements, throws on any modification.Arrays.asList(array): fixed-size view backed by the array;setworks and writes through to the array,add/removethrow.Collections.unmodifiableList(list): read-only view; changes to the underlying list are still visible through it.List.copyOf(list): an immutable copy.
Q35. How does PriorityQueue work? [M]
A binary min-heap stored in an array. offer and poll are O(log n), peek is O(1). Pass a Comparator for a max-heap or custom order: new PriorityQueue<>(Comparator.reverseOrder()). Iteration order is not sorted. Common interview uses: top-K elements, merging K sorted lists, Dijkstra’s algorithm.
6. Generics
Q36. What is type erasure? [M]
Generic type information exists only at compile time. The compiler checks types, inserts casts, and then erases type parameters to their bounds (Object by default). Consequences: you cannot write new T(), T[] creation, instanceof List<String>, or overload methods that differ only by type parameter (m(List<String>) and m(List<Integer>) clash). Erasure kept Java 5 generic code compatible with old bytecode.
Q37. Explain ? extends T, ? super T and PECS. [M]
List<? extends Number>: you can readNumbers but cannot add (exceptnull), because the real list might beList<Integer>.List<? super Integer>: you can addIntegers, but reads only giveObject.- PECS: “Producer Extends, Consumer Super”.
Collections.copy(List<? super T> dest, List<? extends T> src)is the standard example.
Q38. Why is List<Integer> not a subtype of List<Number>? [M]
If it were, you could do List<Number> nums = ints; nums.add(3.14); and put a Double into a list of Integers. Generics are invariant to prevent this. Arrays are covariant (Integer[] is a Number[]), which is why storing the wrong type into an array fails at runtime with ArrayStoreException instead of at compile time.
7. Exceptions
Q39. Checked vs unchecked exceptions? [J]
Checked exceptions (subclasses of Exception but not RuntimeException, e.g. IOException) must be caught or declared with throws. Unchecked exceptions (RuntimeException and subclasses such as NullPointerException, IllegalArgumentException) do not need to be declared. Errors (OutOfMemoryError, StackOverflowError) signal serious JVM problems that applications should not normally catch. Modern frameworks (Spring, most libraries) lean toward unchecked exceptions; checked exceptions also do not fit well with lambdas.
Q40. What is try-with-resources? [J]
try (var in = Files.newBufferedReader(path); var out = Files.newBufferedWriter(target)) {
in.transferTo(out);
}
Any AutoCloseable declared in the header is closed automatically, in reverse order, even when an exception is thrown. If both the body and close() throw, the close() exception is attached as a suppressed exception (e.getSuppressed()) instead of hiding the original.
Q41. final vs finally vs finalize? [J]
final is a modifier (Q6). finally is a block that runs after try/catch whether or not an exception occurred (except when the JVM exits or the thread is killed). finalize() was a cleanup hook called by the GC; it is deprecated for removal because it is unpredictable and slow. Use try-with-resources or java.lang.ref.Cleaner.
Q42. What are exception handling best practices? [M]
- Catch the most specific exception you can handle; do not catch
ExceptionorThrowablejust to log and continue. - Never swallow exceptions with an empty
catch. - Wrap low-level exceptions with context and keep the cause:
throw new OrderException("Order " + id + " failed", e);. - Do not use exceptions for normal control flow.
- Restore the interrupt flag when catching
InterruptedException:Thread.currentThread().interrupt();.
8. Lambdas, Functional Interfaces and Streams
Q43. What is a functional interface? [J]
An interface with exactly one abstract method, which a lambda or method reference can implement. @FunctionalInterface makes the compiler check this. The java.util.function package provides the common ones:
| Interface | Method | Example use |
|---|---|---|
Function<T, R> |
R apply(T) |
map |
Predicate<T> |
boolean test(T) |
filter |
Consumer<T> |
void accept(T) |
forEach |
Supplier<T> |
T get() |
Lazy values, orElseGet |
BiFunction<T, U, R> |
R apply(T, U) |
merge, reduce |
UnaryOperator<T> / BinaryOperator<T> |
Same type in and out | replaceAll, reduce |
Q44. What does “effectively final” mean for lambdas? [J]
A lambda can only use local variables from the enclosing scope that are never re-assigned after initialization. The lambda captures the value, and allowing changes would create confusing races between the variable and the captured copy. To accumulate, use an AtomicInteger, an array, or (better) a stream reduce/collect.
Q45. Intermediate vs terminal stream operations? [J]
Intermediate operations (filter, map, flatMap, sorted, distinct, limit) return a new stream and are lazy: nothing runs until a terminal operation (collect, forEach, reduce, count, findFirst, anyMatch, toList) is called. Streams can be consumed only once. Short-circuiting operations (findFirst, anyMatch, limit) can stop early, even on infinite streams.
Q46. map vs flatMap? [J]
map transforms each element into exactly one element. flatMap transforms each element into a stream and concatenates the results, which flattens nested structures: orders.stream().flatMap(o -> o.items().stream()). Optional has the same pair. Java 16 added mapMulti as an imperative alternative to flatMap.
Q47. Write common Collectors queries. [M]
From Streams.java:
// average salary per department
es.stream().collect(groupingBy(Employee::dept, averagingDouble(Employee::salary)));
// second-highest distinct salary
es.stream().map(Employee::salary).distinct()
.sorted(Comparator.reverseOrder()).skip(1).findFirst();
// highest earner per department
es.stream().collect(groupingBy(Employee::dept, maxBy(comparingDouble(Employee::salary))));
// split into two groups by a condition
es.stream().collect(partitioningBy(e -> e.salary() >= 110, mapping(Employee::name, toList())));
toMap throws IllegalStateException on duplicate keys unless you pass a merge function: toMap(k, v, (a, b) -> a).
Q48. When should you not use parallel streams? [S]
Parallel streams run on the shared ForkJoinPool.commonPool(). Avoid them for small data, for blocking I/O (it starves the common pool for the whole JVM), for operations with shared mutable state, for sources that split poorly (LinkedList, Stream.iterate), and when order-dependent operations (limit, findFirst on ordered streams) dominate. Measure with JMH before and after; parallel is often slower.
Q49. How should Optional be used? [M]
As a return type that says “this might be absent”. Use map, filter, orElse, orElseGet (lazy), orElseThrow. Do not use it for fields, method parameters or collections (return an empty collection instead), and do not call get() without checking. orElse(expensiveCall()) always evaluates the argument; use orElseGet(() -> expensiveCall()).
Q50. What are Stream Gatherers? [S]
Final in Java 24 (JEP 485). stream.gather(gatherer) adds custom intermediate operations, the way collect allows custom terminal ones. Built-ins in java.util.stream.Gatherers include windowFixed, windowSliding, fold, scan and mapConcurrent:
Stream.of(1, 2, 3, 4, 5).gather(Gatherers.windowFixed(2)).toList(); // [[1, 2], [3, 4], [5]]
9. Modern Java: Records, Sealed Types, Pattern Matching
Q51. What is a record? [J]
A concise, immutable data carrier (final in Java 16). record Point(int x, int y) {} generates a canonical constructor, private final fields, accessors (x(), not getX()), equals, hashCode and toString. Records are implicitly final, cannot extend other classes, but can implement interfaces, have static members and extra methods. Use a compact constructor for validation, as in Circle in Shapes.java. Records are shallowly immutable: a List component can still be mutated unless you copy it.
Q52. What are sealed classes and interfaces? [M]
Final in Java 17. sealed interface Shape permits Circle, Rectangle, Square {} restricts which classes can implement it. Each permitted subclass must be final, sealed or non-sealed. Sealed hierarchies let the compiler check that a switch covers every case, so adding a new shape becomes a compile error everywhere it is not handled. This is Java’s take on algebraic data types.
Q53. What is pattern matching for switch, and what are record patterns? [M]
Final in Java 21. switch can match on types, deconstruct records, and add guards with when:
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle(double w, double h) -> w * h; // record pattern
case Square s when s.side() == 0 -> 0; // guard
case Square s -> s.side() * s.side();
}; // no default: the compiler knows Shape is sealed
}
Earlier, Java 16 finalized pattern matching for instanceof (if (obj instanceof String s && !s.isEmpty())), and Java 22 finalized unnamed variables and patterns (case Rectangle(var w, _)). Primitive types in patterns are still a preview feature in Java 27 (JEP 532).
Q54. Switch statements vs switch expressions? [J]
Switch expressions (Java 14) return a value, use case X -> arrows with no fall-through, must be exhaustive, and use yield inside a block to return a value. The old statement form with case X: and break still exists. Prefer arrows.
Q55. What are scoped values? [S]
Final in Java 25 (JEP 506). A ScopedValue shares immutable data with code called within a bounded scope, as a safer and cheaper replacement for ThreadLocal when you use many virtual threads. Values are bound with ScopedValue.where(KEY, value).run(...), cannot be changed inside the scope, and disappear when the scope ends, so they do not leak like forgotten ThreadLocals.
10. Concurrency and Multithreading
Q56. Process vs thread? How do you create a thread? [J]
A process has its own memory; threads within a process share the heap but have their own stacks. Create threads by passing a Runnable to Thread (Thread.ofPlatform().start(task) or new Thread(task).start()), or, much better, submit tasks to an ExecutorService. Calling run() instead of start() runs the task on the current thread.
Q57. What are the thread states? [J]
NEW, RUNNABLE (running or ready), BLOCKED (waiting for a monitor lock), WAITING (wait(), join(), LockSupport.park() with no timeout), TIMED_WAITING (sleep, wait(ms)), TERMINATED.
Q58. What does synchronized guarantee? [M]
Mutual exclusion (only one thread holds a given object’s monitor at a time) and visibility (changes made before releasing the lock are visible to the next thread that acquires it). A synchronized instance method locks this; a static one locks the Class object. Locks are re-entrant: a thread holding a lock can acquire it again.
Q59. What does volatile do, and when is it not enough? [M]
A volatile field is always read from and written to main memory in a way that is visible to all threads, and it prevents certain reorderings (it establishes a happens-before edge between a write and later reads). It does not make compound actions atomic: count++ on a volatile int is still a read-modify-write race. Use AtomicInteger, LongAdder or a lock for that. Typical correct uses: a stop flag, and the instance field in double-checked locking (Singletons.java).
Q60. What is the Java Memory Model’s happens-before? [S]
A set of rules that guarantee when one thread’s writes are visible to another: actions in a thread happen-before later actions in that thread; unlocking a monitor happens-before every later lock of it; a volatile write happens-before later reads of it; Thread.start() happens-before the started thread’s actions; a thread’s actions happen-before another thread’s successful join() on it. Without such an edge, the JIT and CPU may reorder or cache writes, and another thread can see stale or partial data.
Q61. What is a deadlock, and how do you prevent it? [M]
Two or more threads each hold a lock the other needs, so all wait forever. The four conditions are mutual exclusion, hold and wait, no preemption, and circular wait. Prevent it by always acquiring locks in a global order, using tryLock with timeouts, keeping lock scopes small, and not calling unknown code while holding a lock. Diagnose with a thread dump (jcmd <pid> Thread.print or jstack), which reports detected deadlocks.
Q62. wait/notify vs Lock and Condition? [M]
wait, notify and notifyAll must be called while holding the object’s monitor, and wait must be in a while loop that re-checks the condition because of spurious wakeups. ReentrantLock offers the same plus tryLock, timeouts, interruptible locking, fairness, and multiple Conditions per lock, which BoundedBuffer.java uses for “not full” and “not empty”. In real code, use ArrayBlockingQueue or LinkedBlockingQueue instead of writing your own.
Q63. How do thread pools work? What are the ThreadPoolExecutor parameters? [M]
A pool reuses threads to run submitted tasks from a queue. ThreadPoolExecutor(core, max, keepAlive, unit, queue, threadFactory, rejectionHandler): it keeps core threads, queues tasks when they are busy, adds threads up to max only when the queue is full, and applies the rejection policy when both are exhausted. Classic pitfalls: Executors.newFixedThreadPool uses an unbounded queue (memory risk under load), and newCachedThreadPool can create unbounded threads. Always shut pools down; since Java 19 ExecutorService is AutoCloseable, so try-with-resources works.
Q64. Future vs CompletableFuture? [M]
Future.get() blocks and offers no way to chain work. CompletableFuture supports non-blocking composition: thenApply (map), thenCompose (flatMap for async steps), thenCombine (join two), allOf/anyOf, exceptionally/handle for errors, and orTimeout/completeOnTimeout. Without an executor argument, async stages run on the common ForkJoinPool; pass your own executor for blocking I/O. With virtual threads, many teams now prefer plain blocking code over long CompletableFuture chains.
Q65. Atomic* classes, CAS and LongAdder? [M]
AtomicInteger, AtomicLong and AtomicReference use compare-and-swap (CAS) CPU instructions for lock-free atomic updates (incrementAndGet, compareAndSet, updateAndGet). Under heavy contention many CAS retries fail; LongAdder spreads updates across cells and sums them when read, which is faster for counters written by many threads (Concurrency.java).
Q66. What is ThreadLocal, and what is the risk? [M]
Each thread gets its own copy of the value; used for per-request context and non-thread-safe objects like the legacy SimpleDateFormat. In thread pools, threads are reused, so values leak between requests and keep objects alive unless you call remove() in a finally block. With millions of virtual threads, ThreadLocals also cost memory; scoped values (Q55) are the modern alternative.
11. Virtual Threads and Structured Concurrency
Q67. What are virtual threads? [M]
Final in Java 21 (JEP 444). Lightweight threads managed by the JVM instead of the OS. Many virtual threads are multiplexed onto a small pool of carrier platform threads. When a virtual thread blocks on I/O, the JVM unmounts it and the carrier runs another one. You can have millions of them, so the simple “one thread per request” blocking style scales without reactive frameworks.
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i -> executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return i;
}));
} // waits for all tasks
Spring Boot enables them for request handling with spring.threads.virtual.enabled=true.
Q68. When do virtual threads not help? [S]
- CPU-bound work: you still have only as many cores as you have. Use a platform thread pool sized to the cores.
- Pinning: before Java 24, blocking inside a
synchronizedblock pinned the virtual thread to its carrier. JEP 491 (Java 24) removed that forsynchronized; blocking inside native code can still pin. - Do not pool them. Create a new virtual thread per task; limit concurrency to a downstream resource with a
Semaphore, not a small pool. - Heavy
ThreadLocaluse multiplies memory by the number of threads.
Q69. What is structured concurrency? [S]
A model where concurrent subtasks are treated as a unit within a scope: if one fails, the others are cancelled, and the scope does not exit until all have finished, so threads never leak. In Java it is StructuredTaskScope, which is still a preview API in Java 27 (JEP 533, seventh preview) and has changed between releases. Explain the idea and mention its preview status rather than writing exact API calls from memory.
12. JVM, Memory and Garbage Collection
Q70. Describe the JVM memory areas. [M]
- Heap: all objects and arrays, shared by threads, managed by the GC.
- Stack (per thread): frames with local variables, operand stacks and return addresses. Deep recursion causes
StackOverflowError. - Metaspace: class metadata, in native memory since Java 8 (replaced PermGen).
- Code cache: JIT-compiled machine code.
- Program counter registers and native method stacks per thread.
Q71. How does garbage collection work? [M]
The GC finds objects reachable from GC roots (thread stacks, static fields, JNI references) and reclaims everything else. Most collectors are generational, because most objects die young: new objects go to the young generation (Eden plus survivor spaces), collected often and cheaply; survivors are promoted to the old generation, collected less often.
Q72. Compare the main garbage collectors. [S]
| Collector | Goal | Notes |
|---|---|---|
| Serial | Small heaps, single core | One thread, stop-the-world |
| Parallel | Throughput | Multiple threads, stop-the-world; good for batch jobs |
| G1 | Balanced latency and throughput | Default on server-class machines since Java 9; Java 27 makes it the default in all environments (JEP 523). Region-based, aims at a pause-time target (-XX:MaxGCPauseMillis) |
| ZGC | Very low pause times | Concurrent; generational since Java 21 and the only mode since Java 24; pauses typically under a millisecond even on huge heaps |
| Shenandoah | Low pause times | Concurrent compaction; generational mode final in Java 25 |
Pick G1 by default, ZGC for latency-sensitive services with large heaps, Parallel for throughput batch jobs.
Q73. Can Java have memory leaks? [M]
Yes. GC only frees unreachable objects, so anything still referenced stays. Common causes: static collections that only grow, caches without eviction, listeners never removed, ThreadLocals in pools, unclosed resources, and inner class instances holding outer references. Diagnose with a heap dump (jcmd <pid> GC.heap_dump file.hprof) in Eclipse MAT or VisualVM, and with Java Flight Recorder.
Q74. What is the JIT compiler? [S]
The JVM starts by interpreting bytecode, profiles which methods are hot, and compiles them to machine code: quickly with the C1 compiler, then with heavy optimizations with C2 (tiered compilation). Optimizations include inlining, escape analysis (allocating non-escaping objects on the stack or removing them entirely), loop unrolling, and speculative optimizations that are undone (“deoptimized”) if assumptions break. This is why microbenchmarks need warm-up; use JMH. Project Leyden’s ahead-of-time cache features (Java 24 to 26) reduce startup and warm-up time.
Q75. How does class loading work? [S]
Loading, linking (verification, preparation, resolution) and initialization. Class loaders form a hierarchy (bootstrap, platform, application) and use parent delegation: a loader asks its parent first, so core classes cannot be replaced. A class’s identity is its name plus its loader, which is why the same class loaded by two loaders gives a ClassCastException, a common issue in app servers and plugin systems.
Q76. Which JVM options and tools should you know? [M]
-Xms/-Xmx (heap size), -XX:MaxRAMPercentage (heap as a share of container memory), -XX:+UseZGC, -Xlog:gc* (GC logging), -XX:+HeapDumpOnOutOfMemoryError. Tools: jcmd (one tool for most diagnostics), jstack, jmap, Java Flight Recorder with JDK Mission Control, VisualVM, async-profiler.
13. Design Patterns in Java
Q77. How do you write a thread-safe singleton? [M]
Three answers, all in Singletons.java:
- Enum singleton:
enum Registry { INSTANCE; }. Safe against serialization and reflection. Recommended in Effective Java. - Holder idiom: a private static nested class holds the instance; the JVM initializes it lazily and thread-safely on first access.
- Double-checked locking: works only if the field is
volatile; otherwise another thread can see a partly constructed object.
Then say that in Spring applications singletons are usually beans managed by the container, and global singletons make testing harder.
Q78. Which design patterns appear in the JDK? [M]
| Pattern | JDK example |
|---|---|
| Builder | StringBuilder, HttpRequest.newBuilder(), Stream.builder() |
| Factory method | List.of, Calendar.getInstance, Executors.newFixedThreadPool |
| Iterator | Iterator, enhanced for |
| Decorator | BufferedInputStream(new FileInputStream(...)) |
| Adapter | Arrays.asList, InputStreamReader |
| Strategy | Comparator passed to sort |
| Observer | java.beans.PropertyChangeListener, Flow (reactive streams) |
| Template method | AbstractList, HttpServlet.service |
| Proxy | java.lang.reflect.Proxy, Spring AOP |
Q79. What is dependency injection? [M]
Objects receive their dependencies from outside instead of creating them, which makes code easier to test (pass a fake) and to reconfigure. Prefer constructor injection: dependencies can be final, the object is never half-initialized, and tests do not need a framework. Spring, Micronaut, Quarkus and Dagger are common DI frameworks.
14. Spring Boot, JPA and Testing
Q80. What does Spring Boot add on top of Spring? [J]
Auto-configuration (sensible beans based on what is on the classpath), starter dependencies, an embedded server (Tomcat, Jetty or Undertow), externalized configuration (application.yml, environment variables, profiles), and production features through Actuator (health, metrics, info endpoints). Spring Boot 3 moved to Jakarta EE namespaces (jakarta.*) and requires Java 17; Spring Boot 4 (November 2025) builds on Spring Framework 7. Check the Spring Boot docs for the current baseline.
Q81. What are bean scopes and the bean lifecycle? [M]
Scopes: singleton (default, one per container), prototype (new each injection), and web scopes request, session, application. Lifecycle: instantiate, inject dependencies, Aware callbacks, BeanPostProcessor before-init, @PostConstruct, after-init (where proxies for @Transactional and AOP are created), use, @PreDestroy on shutdown. Injecting a prototype into a singleton gives one fixed instance; use ObjectProvider to get a new one each time.
Q82. How does @Transactional work, and when does it silently not work? [S]
Spring wraps the bean in a proxy that opens a transaction before the method and commits or rolls back after. It does not apply when:
- The method is called from another method in the same class (self-invocation bypasses the proxy).
- The method is
private(proxies can only intercept methods they can override or implement). - The exception is checked: by default only unchecked exceptions and errors trigger rollback; use
rollbackFor. - The exception is caught inside the method and not rethrown.
Also know propagation (REQUIRED, REQUIRES_NEW) and isolation levels.
Q83. What is the N+1 query problem in JPA/Hibernate? [M]
Loading N parent entities with one query, then lazily loading each one’s association with another query: N+1 queries total. Fixes: JOIN FETCH in JPQL, @EntityGraph, batch fetching (@BatchSize or hibernate.default_batch_fetch_size), or DTO projections that select only what you need. Detect it by logging SQL in tests or counting statements.
Q84. Lazy vs eager loading? What is LazyInitializationException? [M]
LAZY loads an association only when accessed (default for @OneToMany and @ManyToMany); EAGER loads it immediately (default for @ManyToOne and @OneToOne, which many teams override to LAZY). Accessing a lazy association after the persistence context is closed throws LazyInitializationException. Fix it by fetching what you need inside the transaction (fetch joins, entity graphs, DTOs), not by turning on open-session-in-view or making everything eager.
Q85. How do you test Java applications? [M]
- Unit tests with JUnit (JUnit Jupiter) and AssertJ, mocking collaborators with Mockito.
- Slice tests in Spring:
@WebMvcTest(controllers only),@DataJpaTest(repositories). - Integration tests with
@SpringBootTestand real dependencies in containers via Testcontainers, which is more reliable than in-memory database substitutes. - Contract and end-to-end tests where services talk to each other.
Good senior answers include the test pyramid, test speed, and avoiding over-mocking.
15. Coding Round
All solutions are in src/main/java/interview, with tests in AllTests.java.
| Exercise | File | What interviewers check |
|---|---|---|
LRU cache with O(1) get/put |
LruCache.java |
HashMap + doubly linked list, sentinel nodes |
| Producer-consumer with a bounded buffer | BoundedBuffer.java |
Locks, conditions, while around await |
| Thread-safe singleton (3 ways) | Singletons.java |
volatile, class initialization |
| Print odd/even numbers with two threads | Concurrency.java |
wait/notifyAll, shared state |
Lost updates vs LongAdder |
Concurrency.java |
Atomicity |
| Virtual threads executor | Concurrency.java |
Java 21 API |
| Sealed shapes with pattern matching | Shapes.java |
Records, exhaustive switch |
Immutable value class with equals/hashCode |
Money.java |
Contract, defensive design |
| Reverse, palindrome, anagram, first non-repeated character | Strings.java |
Two pointers, groupingBy with LinkedHashMap |
| Stream queries on employees | Streams.java |
groupingBy, partitioningBy, maxBy |
Q86. Implement an LRU cache. [M]
Two ways. Quick: extend LinkedHashMap with accessOrder = true and override removeEldestEntry to return size() > capacity. Expected in most interviews: a HashMap<K, Node> for O(1) lookup plus a doubly linked list with sentinel head/tail nodes for O(1) “move to front” and “remove last”. LruCache.java shows the second. Practice on LeetCode 146: LRU Cache.
Q87. Implement producer-consumer. [M]
Show the BlockingQueue version first (put blocks when full, take blocks when empty), then the manual version with ReentrantLock and two Conditions, or synchronized with wait/notifyAll. Key points: wait in a while loop, signal the other side after each change, unlock in finally, and handle InterruptedException properly.
Q88. Find the first non-repeated character. [J]
Count characters in a LinkedHashMap (which keeps insertion order), then return the first with count 1. O(n) time. With streams: groupingBy(identity(), LinkedHashMap::new, counting()). See LeetCode 387: First Unique Character in a String.
Q89. Classic LeetCode problems to practice in Java
| Problem | Java focus |
|---|---|
| 1. Two Sum | HashMap |
| 20. Valid Parentheses | ArrayDeque as a stack |
| 49. Group Anagrams | computeIfAbsent |
| 125. Valid Palindrome | Two pointers, Character methods |
| 146. LRU Cache | Linked list + map |
| 215. Kth Largest Element in an Array | PriorityQueue |
| 347. Top K Frequent Elements | Map + heap |
| 1114. Print in Order | Thread coordination |
| 1115. Print FooBar Alternately | Semaphore or wait/notify |
| 1116. Print Zero Even Odd | Three-thread coordination |
16. Output and Trick Questions
1.
Integer a = 127, b = 127, c = 128, d = 128;
System.out.println((a == b) + " " + (c == d));
Answer
`true false` with default JVM settings. `Integer.valueOf` caches -128 to 127, so `a` and `b` are the same object; `128` creates two objects. Always use `equals` for wrappers.2.
String s1 = "java";
String s2 = "ja" + "va";
String part = "ja";
String s3 = part + "va";
System.out.println((s1 == s2) + " " + (s1 == s3) + " " + (s1 == s3.intern()));
Answer
`true false true`. `"ja" + "va"` is a compile-time constant, so it is the same pooled literal. `part + "va"` is computed at runtime and creates a new object. `intern()` returns the pooled instance.3.
static int f() {
try { return 1; }
finally { return 2; }
}
Answer
`2`. A `return` in `finally` overrides the `try`'s return (and would also swallow an exception). Compilers and linters warn about this.4.
List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
list.remove(1);
System.out.println(list);
Answer
`[1, 3]`. `remove(int index)` is chosen over `remove(Object)` because `1` is an `int` and no boxing is needed. Use `list.remove(Integer.valueOf(1))` to remove the value.5.
List<String> names = new ArrayList<>(List.of("a", "b", "c"));
for (String n : names) if (n.equals("b")) names.remove(n);
System.out.println(names);
Answer
Prints `[a, c]` with no exception, which surprises most people. After removing `"b"` (the second-to-last element), the size becomes 2 and `hasNext()` returns `false`, so the iterator never calls `next()` and never checks for modification. Remove `"a"` instead and you get a `ConcurrentModificationException`. Use `removeIf`.6.
System.out.println(0.1 + 0.2 == 0.3);
System.out.println(new BigDecimal("0.1").add(new BigDecimal("0.2")).equals(new BigDecimal("0.3")));
System.out.println(new BigDecimal("2.0").equals(new BigDecimal("2.00")));
Answer
`false true false`. Doubles are binary floating point. `BigDecimal` from strings is exact, but `equals` also compares **scale**, so `2.0` and `2.00` differ; use `compareTo(...) == 0`. Never use `new BigDecimal(0.1)` (the double constructor), which captures the binary error.7.
char c = 'A';
c += 1;
// c = c + 1; // does this line compile?
System.out.println(c);
Answer
Prints `B`. Compound assignment includes an implicit cast back to `char`. The commented line does not compile: `c + 1` is an `int`, and assigning an `int` to a `char` needs an explicit cast.8.
Map<String, Integer> m = new HashMap<>();
m.put(null, 1);
Map<String, Integer> cm = new ConcurrentHashMap<>();
cm.put(null, 1);
Answer
The `HashMap` accepts a `null` key. The `ConcurrentHashMap` line throws `NullPointerException`: it forbids `null` keys and values so that `null` from `get` unambiguously means "absent" in concurrent code.Best Resources to Prepare
| Resource | Type | Cost | Best for |
|---|---|---|---|
| dev.java Learn | Official tutorials | Free | Best free pick: modern Java from the Java team, including records, pattern matching and virtual threads |
| Java SE documentation | Docs | Free | API docs, language and JVM specifications, GC tuning guide |
| Java Language Specification | Spec | Free | Exact rules for tricky questions |
| JEP index | Specs | Free | What each feature does and when it became final |
| Inside Java | Blog, podcast | Free | News and deep dives from the Java team at Oracle |
| Baeldung | Articles | Free (some courses paid) | Focused how-to articles for Java and Spring |
| Spring Guides and Spring Boot reference | Docs | Free | Spring interview prep |
| JUnit User Guide | Docs | Free | Testing questions |
| Testcontainers for Java | Docs | Free | Integration testing |
| Effective Java, 3rd edition, by Joshua Bloch (publisher page) | Book | Paid | Best book pick: idioms interviewers love (builders, immutability, equals/hashCode, generics) |
| Java Concurrency in Practice by Brian Goetz and others | Book | Paid | The classic on threads and the memory model (predates virtual threads) |
| Modern Java in Action by Raoul-Gabriel Urma, Mario Fusco and Alan Mycroft (Manning) | Book | Paid | Lambdas, streams, CompletableFuture |
| JMH | Tool | Free | Correct microbenchmarks |
| LeetCode | Practice | Free tier, Premium paid | Coding rounds in Java |
FAQ
What Java interview questions are asked for freshers?
OOP pillars, abstract class vs interface, overloading vs overriding, String immutability, == vs equals, ArrayList vs LinkedList, HashMap basics, checked vs unchecked exceptions, final/finally/finalize, and simple coding (reverse a string, find duplicates, two sum).
What do senior Java interviews focus on? Concurrency and the memory model, JVM and GC tuning, diagnosing production issues (thread dumps, heap dumps, profiling), modern Java features, Spring internals (proxies, transactions), database access patterns (N+1, transactions, connection pools), and system design.
Do I still need to know Java 8?
Yes. Lambdas, streams and Optional (all Java 8) remain the most asked “modern” topics, and many companies still maintain Java 8 or 11 code. But also know records, switch expressions, text blocks, sealed classes and virtual threads.
Which Java version should I use in a coding interview?
Whatever the platform supports; most online judges offer Java 17 or 21. Use var, List.of, records and enhanced switch if available, but do not rely on preview features.
How do I explain HashMap internals in two minutes?
Array of buckets, index from the spread hash and capacity - 1, collisions in a list that turns into a red-black tree past 8 entries, resize by doubling at 75% load, O(1) average, keys need consistent equals/hashCode, not thread-safe.
Is Java still worth learning in 2027? Java is still widely used for backend services, Android (alongside Kotlin), big data (Kafka, Spark, Flink are JVM-based) and enterprise systems, and a new feature release ships every six months. Virtual threads and the newer language features have made it more pleasant to write than its reputation suggests.
Where to Go Next
- Backend rounds: backend-interview-questions covers APIs, databases, caching, queues and scaling.
- System design: system-design-case-studies and system-design-interview-questions.
- Algorithms: leetcode-patterns and blind-75-leetcode-solutions.
- Quick reference: interviews-cheatsheets, and tech-interview-handbook-behavioral for behavioral rounds.
- Kubernetes for Java services: kubernetes-cheatsheet.
Contributing
Pull requests are welcome: new questions, clearer answers, version updates when a new JDK ships, and more tested exercises. Please:
- Write in your own words and keep answers short and accurate.
- Mark the level ([J], [M], [S]) and the Java version for newer features, and say when an API is still in preview.
- Put code in
src/main/java/interview, add a check toAllTests.java, and make sure./run-tests.shpasses on JDK 21. - Link primary sources (JEPs, Java SE docs) for version claims.
License
The code in this repository is released under the MIT License.
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.