Java interview questions (2026)

Modern Java from equals and hashCode to virtual threads and heap dumps, with what a strong answer sounds like.

These Java interview questions target modern Java, meaning Java 21 as the baseline and Java 25 (the newest LTS, released in September 2025) where it matters. They are for engineering managers and technical recruiters building a screening round, and for developers checking whether their knowledge is current. Each question includes what a good answer covers and, where useful, a red flag. Choose 6 to 8 at the right level. For seniors, spend more time on the scenarios and less on definitions.

What a strong Java interview checks

  • Object model: equality, immutability and how the collections depend on them.
  • Modern language features: records, sealed types, pattern matching and the right use of Optional and streams.
  • Concurrency: visibility, atomicity, concurrent collections and virtual threads.
  • JVM awareness: garbage collection, memory leaks and the diagnostic tools.
  • Production habits: resource handling, batching and debugging under load.

Java interview questions: core language

1. What is the contract between equals and hashCode?

What good looks like: if two objects are equal by equals(), they must return the same hashCode(). The reverse isn't required, since collisions are allowed. Override both together or HashMap and HashSet will fail to find objects you put in. A strong answer adds that fields used in hashCode() shouldn't change while the object is a key, and that records generate both methods for you.

Red flag: overriding equals() alone "because that's what comparison uses."

2. Why are Strings immutable, and why should you avoid == for comparing them?

What good looks like: immutability makes strings safe to share across threads, safe as map keys (the hash can be cached), and safe for security-sensitive values like file paths. String literals are interned in a pool, so == sometimes returns true by accident. Always compare content with equals(). For building strings in a loop, use StringBuilder.

3. Checked or unchecked exceptions: how do you decide?

What good looks like: checked exceptions (subclasses of Exception but not RuntimeException) must be declared or caught, and suit recoverable conditions the caller should handle. Unchecked exceptions signal programming errors or conditions the caller can't reasonably fix. Many modern codebases favor unchecked exceptions with clear types. A strong candidate never catches and ignores an exception, and wraps with a cause so the stack trace survives.

4. How does HashMap work internally?

What good looks like: keys are hashed into an array of buckets, and equals() resolves collisions within a bucket. When the size passes the load factor (0.75 by default), the table doubles and entries are redistributed. Since Java 8, a bucket with many collisions turns into a balanced tree, so worst-case lookups are O(log n) instead of O(n). It isn't thread-safe.

Red flag: no idea why a mutable key can "disappear" from a map.

5. What does type erasure mean for generics?

What good looks like: generic type parameters exist at compile time and are mostly erased at runtime. So List<String> and List<Integer> share one runtime class, you can't write new T(), and you can't check instanceof List<String>. Strong candidates explain wildcards with "producer extends, consumer super": read from List<? extends Number>, write to List<? super Integer>.

6. When would you use a record, and when not?

What good looks like: records (standard since Java 16) are for transparent data carriers. They give you a canonical constructor, accessors, equals(), hashCode() and toString(). Fields are final, but immutability is shallow: a record holding a List can still have that list changed unless you copy it with List.copyOf in a compact constructor. Records can't extend another class. They are a poor fit for JPA entities, which need a no-arg constructor and mutable state.

7. How do sealed interfaces and pattern matching for switch work together?

What good looks like: a sealed interface lists the classes allowed to implement it, for example sealed interface Shape permits Circle, Square. With pattern matching for switch (final in Java 21), a switch over a Shape can match each record type and pull out its fields with record patterns. Because the compiler knows every subtype, the switch is exhaustive without a default, and adding a new shape becomes a compile error until each switch handles it.

8. What is Optional for, and how is it misused?

What good looks like: Optional is a return type that says "this might be empty" so callers must handle that case. Use map, orElse, orElseGet and orElseThrow. Common misuse: calling get() without checking, using Optional for fields or method parameters, and wrapping collections (return an empty list instead).

9. Explain how streams are evaluated.

What good looks like: intermediate operations like filter and map are lazy, and nothing runs until a terminal operation like collect or count. A stream can only be consumed once. Stream.toList() (Java 16) returns an unmodifiable list. Parallel streams use the common fork-join pool, so they can hurt more than help for small inputs, blocking work or shared mutable state.

Concurrency and the JVM

10. What is the difference between volatile and synchronized?

What good looks like: volatile guarantees visibility, so every thread sees the latest write, and prevents certain reordering. It doesn't make compound actions atomic, so count++ on a volatile field is still a race. synchronized gives both mutual exclusion and visibility. For counters, use AtomicInteger or LongAdder.

Red flag: "volatile makes it thread-safe."

11. What are virtual threads, and when do they help?

What good looks like: virtual threads (final in Java 21) are lightweight threads managed by the JVM and mounted on a small set of platform carrier threads. They make the simple thread-per-request style scale to very large numbers of concurrent blocking I/O tasks. They don't make CPU-bound work faster. Don't pool them: create one per task, for example with Executors.newVirtualThreadPerTaskExecutor(). Strong candidates know that blocking inside synchronized used to pin the carrier thread, a limit removed in Java 24, and that large per-thread ThreadLocal caches become costly with millions of threads. Scoped values, final in Java 25, are the suggested alternative for sharing context.

12. ConcurrentHashMap or Collections.synchronizedMap?

What good looks like: synchronizedMap wraps every call in one lock, so threads queue up. ConcurrentHashMap allows concurrent reads and fine-grained writes, and its iterators are weakly consistent rather than throwing ConcurrentModificationException. Its compute, merge and putIfAbsent methods are atomic. A check-then-put written as two calls is still a race on either map.

13. How does garbage collection work, and can Java leak memory?

What good looks like: objects are collected once nothing reachable refers to them. G1 is the default collector on most servers. ZGC targets very low pause times and is generational in current releases. Yes, Java leaks: objects stay reachable through static collections that only grow, listeners never removed, caches with no eviction, and ThreadLocal values left on pooled threads.

14. What does try-with-resources do that finally doesn't?

What good looks like: any AutoCloseable declared in the try header is closed automatically, in reverse order of opening. If both the body and close() throw, the body's exception wins and the close exception is attached as a suppressed exception, instead of one silently replacing the other.

Practical scenarios

15. A service's heap grows until it crashes with OutOfMemoryError. How do you investigate?

What good looks like: capture a heap dump, either on crash with -XX:+HeapDumpOnOutOfMemoryError or live with jcmd <pid> GC.heap_dump. Open it in a tool like Eclipse MAT and look at the dominator tree to find what retains the most memory. Check GC logs and Java Flight Recorder data for allocation trends. Then fix the retention, not the heap size.

Red flag: "Just raise -Xmx."

16. Build a small in-memory LRU cache.

What good looks like: extend LinkedHashMap with access order turned on (the three-argument constructor with true) and override removeEldestEntry to evict past a size limit. Then point out it isn't thread-safe and that production code would usually use a library like Caffeine, which handles concurrency and expiry.

17. Under load, latency spikes and a thread dump shows many BLOCKED threads. What next?

What good looks like: take several dumps a few seconds apart (jcmd <pid> Thread.print or jstack) and find which lock or monitor the threads wait on and which thread holds it. Common causes are a synchronized method around slow I/O, a single shared resource, or an exhausted connection pool. Fix by narrowing the lock, moving I/O outside it, or sizing the pool from measurements.

18. Load a million rows from a CSV file into a database.

What good looks like: stream the file instead of reading it all into memory (a BufferedReader or Files.lines inside try-with-resources). Use a PreparedStatement with addBatch() and executeBatch() every few thousand rows, commit per batch, and log bad rows for review instead of failing the whole job. Strong candidates also mention the database's own bulk loader when it's an option.

Behavioral (STAR)

19. Tell me about upgrading a service to a newer Java version.

What good looks like: a clear Situation (for example, moving from 17 to 21), how they found breaking changes (build warnings, dependency updates, removed APIs), how they tested and rolled out gradually, and a Result such as lower memory use or the ability to adopt virtual threads.

20. Describe changing a Java codebase that had few tests.

What good looks like: they added characterization tests around the code before changing it, made small steps, and left the area better covered than they found it. Strong candidates explain how they convinced the team the time was worth it.

Red flag: a big rewrite with no safety net.

A simple scoring rubric

ScoreWhat you hear
1Wrong or memorized answers. Confuses volatile with thread safety, or can't explain equals and hashCode.
2Knows the definitions but not the consequences. Unaware of records, virtual threads or how to read a heap or thread dump.
3Correct, current answers with practical examples. Picks the right collection and concurrency tool and explains why.
4A 3, plus failure modes, JVM tooling and trade-offs offered unprompted. Could mentor a mid-level developer.

Running this interview with AI

Java is in NTRVSTA's exam library, so an AI interviewer can run this first round live, by video avatar or audio. The interviewer raises or lowers difficulty based on each answer: a candidate who nails HashMap internals moves to concurrency and JVM scenarios, while one who struggles gets questions closer to the fundamentals. That way both get a fair read in the same time slot.

Your engineers get a score breakdown and video snippets of key answers instead of a stack of calls to sit through. Read how AI interview scoring works before you set a pass mark, and see our comparison of AI interview software for other options. Related question sets: backend developer, system design and SQL.

Questions

Which Java version should interview questions assume in 2026?

Assume Java 21 as the floor, since it is the LTS most teams run, and treat Java 25 features as a bonus. If your codebase is still on 11 or 17, say so and skip questions about virtual threads and pattern matching for switch.

Should a Java interview include Spring questions?

Only if the role uses Spring every day. Start with core Java, because a candidate who understands collections, concurrency and the JVM can learn a framework quickly. Add two or three framework questions at the end for senior hires.

How do I tell a senior Java developer from a mid-level one?

Seniors explain why, not just what. They bring up memory, concurrency and failure modes without being asked, and in the scenario questions they reach for tools like JFR, heap dumps and thread dumps before guessing.

Hiring Java developers this quarter? Book a 20-minute demo to see an adaptive Java round, or try a sample interview yourself first.

NTRVSTA
‍