← All articles
13 min read

Java Interview Questions for Software Engineers (2026 Guide)

The Java interview questions backend engineers actually get in 2026, organized by topic with model answers. Includes the Java 21 and Java 25 features that older question lists still miss.

Java interview questions in 2026 cluster around five areas: core Java and OOP, collections internals, concurrency, the JVM, and Spring Boot. Interviewers for experienced roles focus less on syntax trivia and more on why things work, such as how HashMap resolves collisions, when virtual threads help, and how @Transactional actually starts a transaction. This guide gives you the questions in each area with short model answers, including the Java 21 and Java 25 features that most older lists skip.

Key Takeaways

  • Prepare on Java 21 and know what Java 25 changed. Both are LTS releases, and interviewers increasingly ask about records, sealed classes, pattern matching, and virtual threads.
  • HashMap and ConcurrentHashMap internals are the single most predictable topic for experienced Java candidates. Know the treeify threshold, resize behavior, and why ConcurrentHashMap rejects null.
  • Virtual threads are cheap, so you never pool them. You limit concurrency with a semaphore instead.
  • For the JVM, be ready to explain heap vs stack vs metaspace and when you would pick G1 over ZGC.
  • Spring Boot questions test whether you understand proxies, auto-configuration, and transaction boundaries, not annotation names.
  • Senior interviews swap definitions for production scenarios: leaks, deadlocks, and slow endpoints.

Which Java Interview Questions Come Up by Level?

Question depth scales with seniority. The table below shows what each level is usually expected to answer comfortably, based on common loop structures at product companies and banks.

TopicJunior (0-2 yrs)Mid (2-5 yrs)Senior (5+ yrs)
Core Java and OOPequals/hashCode, String immutability, interfacesGenerics, immutability design, exceptions strategyAPI design trade-offs, records vs classes
CollectionsList vs Set vs MapHashMap internals, iteration fail-fastConcurrentHashMap internals, memory cost of collections
ConcurrencyThread vs Runnable, synchronizedExecutorService, volatile, locksJava memory model, virtual threads, deadlock diagnosis
JVMHeap vs stackGC basics, class loadingGC tuning, heap dumps, JIT behavior
Modern JavaRecords, varSealed classes, switch patternsData-oriented design with sealed hierarchies
Spring BootDI, REST controllersAuto-configuration, @TransactionalProxies, observability, migration to Boot 4

If you are still deciding whether Java is the right choice for the coding rounds themselves, our guide on which language to use in a coding interview compares it with Python and C++.

Core Java and OOP Interview Questions

Core Java questions check whether you understand the language's contracts, not just its keywords. Expect these early in a phone screen.

What is the contract between equals() and hashCode()?

If two objects are equal according to equals(), they must return the same hashCode(). The reverse is not required: unequal objects may share a hash code. Breaking this contract makes hash-based collections misbehave. A key you put into a HashMap becomes impossible to find because lookups go to the wrong bucket.

Why is String immutable?

String is immutable so that it can be safely shared across threads, cached in the string pool, and used as a HashMap key without its hash changing. Immutability also matters for security, since class names, file paths, and connection URLs are passed as strings and must not change after validation.

What is the difference between an abstract class and an interface?

An interface defines a capability that unrelated classes can share, and since Java 8 it can carry default and static methods. An abstract class can hold state and constructors, and it models an "is-a" relationship with shared implementation. A class can implement many interfaces but extend only one class.

Checked vs unchecked exceptions?

Checked exceptions extend Exception and must be declared or caught. Unchecked exceptions extend RuntimeException and signal programming errors. Many modern codebases, including Spring, wrap checked exceptions in unchecked ones because checked exceptions do not compose well with lambdas and streams.

Also rehearse pass-by-value semantics and generic type erasure. For object-oriented design depth, our design patterns interview questions guide covers the patterns Java interviewers ask about most.

Java Collections Interview Questions

Collections internals are where experienced candidates win or lose credibility. Interviewers often start broad and keep asking "and then what happens?"

How does HashMap work internally?

HashMap is an array of buckets. On put, it calls the key's hashCode(), XORs the high 16 bits into the low 16 bits to spread entropy, and masks the result with table.length - 1 to choose a bucket. The table length is always a power of two, which is why masking works.

Collisions are stored in a linked list inside the bucket. Since Java 8, a bucket converts to a red-black tree when it holds more than 8 entries and the table has at least 64 buckets. This keeps worst-case lookups at O(log n) instead of O(n). If the table is smaller than 64, HashMap resizes instead of treeifying.

The default load factor is 0.75. When size exceeds capacity times load factor, the table doubles and entries are redistributed. Each entry either stays at its index or moves by exactly the old capacity, so rehashing is cheap.

Why is HashMap not thread-safe?

Concurrent put calls can overwrite each other's entries and lose data, and a resize running in parallel can leave the table inconsistent. In Java 7 a concurrent resize could even create a circular linked list and an infinite loop on get. Never share a plain HashMap across threads without external synchronization.

How does ConcurrentHashMap achieve thread safety?

In Java 8 and later, ConcurrentHashMap no longer uses segments. It inserts into an empty bucket with a CAS operation and, when a bucket is occupied, locks only that bucket's head node with synchronized. Reads are lock-free because node values and next pointers are volatile. Resizing is cooperative: threads that touch the map during a resize help move buckets.

A common follow-up asks why ConcurrentHashMap rejects null keys and values. The answer is ambiguity. If get returns null, you cannot tell whether the key is absent or mapped to null, and in a concurrent map you cannot safely check with a second call.

Which collection would you use, and why?

NeedUseWhy
Fast lookup by key, single threadHashMapO(1) average
Sorted keys or range queriesTreeMapRed-black tree, O(log n)
Insertion or access orderLinkedHashMapAlso the base for a simple LRU cache
Shared map across threadsConcurrentHashMapBucket-level locking, lock-free reads
Queue between producers and consumersArrayBlockingQueue or LinkedBlockingQueueBlocking put and take
Index access, frequent appendsArrayListContiguous array, cache-friendly
Ordered access to first and lastAny SequencedCollectionJava 21 added getFirst, getLast, reversed

Java 21 introduced SequencedCollection, SequencedSet, and SequencedMap, which give lists, deques, and linked maps a common API for first and last elements.

The LinkedHashMap LRU cache is also a classic live coding prompt. If a round turns into designing a cache at scale, our walkthrough of designing a distributed cache picks up where the in-memory version stops.

The hardest part of a Java phone screen is the third follow-up on HashMap or ConcurrentHashMap internals, when you know the answer but cannot recall it fast enough. TechScreen gives you real-time answers on screen and stays invisible during screen shares on Zoom, Meet, Teams, and CoderPad. Start with 3 free tokens, no credit card.

Get started free →

Java Multithreading and Concurrency Interview Questions

Concurrency questions show whether you can write services that stay correct under load. Our dedicated concurrency and multithreading interview guide goes deeper on classic problems like producer-consumer and the dining philosophers.

What does volatile guarantee?

volatile guarantees visibility and ordering. A write to a volatile field happens-before every later read of that field, so other threads see the latest value. It does not make compound actions atomic, so count++ on a volatile int is still a race. Use AtomicInteger, LongAdder, or a lock for that.

synchronized vs ReentrantLock?

Both provide mutual exclusion and the same memory visibility guarantees. ReentrantLock adds timed and interruptible lock attempts, optional fairness, and multiple condition variables. synchronized is simpler and releases automatically. Prefer synchronized unless you need one of those features.

What are virtual threads?

Virtual threads are lightweight threads managed by the JVM instead of the operating system. They became a standard feature in Java 21 through JEP 444. When a virtual thread blocks on I/O, the JVM unmounts it from its carrier platform thread, which then runs other virtual threads. That lets you write simple blocking code and still handle very large numbers of concurrent requests.

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    List<Future<Order>> futures = orderIds.stream()
        .map(id -> executor.submit(() -> orderClient.fetch(id)))
        .toList();
    for (Future<Order> f : futures) {
        process(f.get());
    }
}

Interviewers usually follow up with three points:

  1. Do not pool virtual threads. They are cheap to create. Pooling them defeats the purpose. To limit pressure on a downstream database, use a Semaphore.
  2. They help I/O-bound work, not CPU-bound work. CPU-heavy tasks still need roughly as many threads as cores.
  3. Pinning. In Java 21, a virtual thread blocking inside a synchronized block pinned its carrier thread, which could exhaust the carrier pool. JEP 491, delivered in Java 24 and included in the Java 25 LTS, removed nearly all of that pinning. On Java 21, the usual advice was to replace synchronized around blocking calls with ReentrantLock.

A senior follow-up may ask about ThreadLocal with millions of virtual threads. The memory cost adds up, which is one reason scoped values were finalized in Java 25 as an immutable, bounded alternative.

JVM Memory and Garbage Collection Questions

JVM questions separate engineers who have debugged production services from those who have only written them.

What are the main JVM memory areas?

The heap stores objects and is shared by all threads. Each thread has its own stack holding frames with local variables and partial results. Metaspace stores class metadata in native memory and replaced PermGen in Java 8. There is also the code cache for JIT-compiled code, plus direct buffers allocated outside the heap.

How does generational garbage collection work?

Most objects die young, so the heap is split into a young generation and an old generation. New objects go into the young generation, which is collected often and cheaply. Objects that survive several collections are promoted to the old generation, which is collected less often.

Which garbage collector would you choose?

CollectorDefault sinceBest forTrade-off
G1Java 9General-purpose servicesBalanced throughput and pauses
ZGC (generational)Generational default since Java 23Low-latency services, large heapsUses more CPU and memory headroom
ParallelOlder defaultBatch jobs, throughputLonger stop-the-world pauses
Serialn/aSmall containers, single coreSingle-threaded collection

A strong answer starts with G1 and only moves to ZGC when tail latency matters, such as a trading gateway or a real-time API with strict p99 targets.

How would you find a memory leak?

Watch whether heap usage after full GC keeps rising. Capture a heap dump with jcmd <pid> GC.heap_dump, open it in Eclipse MAT or a similar tool, and look at the dominator tree for objects retaining unexpected memory. Usual suspects are static collections that only grow, unbounded caches, listeners that are never removed, and ThreadLocal values left on pooled threads.

Modern Java Features Interview Questions (Java 17 to 25)

Modern Java is the area most older question lists miss, and it is where you can stand out.

What is a record?

A record is a concise, immutable data carrier. The compiler generates the constructor, accessors, equals, hashCode, and toString from the components. Records became final in Java 16. Use a compact constructor for validation.

public record Money(BigDecimal amount, String currency) {
    public Money {
        Objects.requireNonNull(amount);
        if (amount.signum() < 0) throw new IllegalArgumentException("negative");
    }
}

Records are shallowly immutable. A record holding a List still exposes a mutable list unless you copy it with List.copyOf.

What are sealed classes, and why pair them with pattern matching?

A sealed class or interface restricts which classes can extend it, using a permits clause. Sealed types became final in Java 17. Combined with record patterns and pattern matching for switch, both final in Java 21, the compiler can check that a switch covers every subtype with no default branch.

sealed interface PaymentResult permits Approved, Declined, Pending {}
record Approved(String txId) implements PaymentResult {}
record Declined(String reason) implements PaymentResult {}
record Pending(Instant retryAt) implements PaymentResult {}

String describe(PaymentResult r) {
    return switch (r) {
        case Approved(var txId) -> "Approved " + txId;
        case Declined(var reason) -> "Declined: " + reason;
        case Pending(var retryAt) -> "Retry at " + retryAt;
    };
}

If someone later adds a new subtype, every exhaustive switch stops compiling. That is the point to make in an interview: the compiler finds missing cases instead of production.

What else changed recently?

  • Unnamed variables (_), final in Java 22, for values you must declare but never use.
  • Scoped values, final in Java 25, for sharing immutable context across a call chain.
  • Flexible constructor bodies, final in Java 25, which allow statements such as argument validation before super(...).
  • Structured concurrency is still a preview API in Java 25, so mention it as upcoming rather than production-ready.

Spring Boot Interview Questions

Spring Boot questions test whether you understand what the framework does for you. Most backend Java roles use it, and our backend engineer interview guide covers the surrounding API and database rounds.

How does auto-configuration work?

Spring Boot reads a list of auto-configuration classes from the classpath and applies each one only if its conditions match, using annotations like @ConditionalOnClass, @ConditionalOnMissingBean, and @ConditionalOnProperty. Add a database driver and a DataSource appears. Define your own DataSource bean and Boot backs off.

How does @Transactional work, and when does it silently fail?

Spring wraps the bean in a proxy that opens a transaction before the method and commits or rolls back after it. Because the proxy intercepts calls from outside, two classic failures appear:

  1. Self-invocation. Calling a @Transactional method from another method in the same class bypasses the proxy, so no transaction starts.
  2. Checked exceptions. By default, rollback happens only for unchecked exceptions and errors. A checked exception commits unless you set rollbackFor.

What is the N+1 query problem?

Loading a list of N entities and then lazily loading a relation for each one triggers N extra queries. Fix it with a fetch join, an @EntityGraph, or batch fetching, and verify by logging SQL in tests.

How do you enable virtual threads in Spring Boot?

Set spring.threads.virtual.enabled=true, supported since Spring Boot 3.2. Request handling and Boot-managed task executors then run on virtual threads. Spring Boot 4.0, released in November 2025 on top of Spring Framework 7, keeps a Java 17 baseline while supporting Java 25.

Senior-Level Java Interview Questions

Senior Java interviews replace definitions with scenarios. The interviewer wants to hear a diagnosis process, not a single answer. Practice explaining your reasoning out loud, since narration is scored as heavily as the conclusion. Our guide to thinking out loud in coding interviews covers how to structure it.

Scenario questions to rehearse:

  • "p99 latency on an endpoint jumped after a deploy. Walk me through it." Check GC logs for longer pauses, thread dumps for lock contention or pool exhaustion, and connection pool metrics before touching code.
  • "The service runs out of memory every few days." Compare heap after full GC over time, capture two heap dumps hours apart, and diff the dominators.
  • "We want to move a thread-pool-based service to virtual threads. What could go wrong?" Pinning on older JDKs, unbounded concurrency overwhelming the database, heavy ThreadLocal usage, and libraries that assume a small fixed thread count.
  • "Design an in-memory rate limiter that is thread-safe." Discuss a token bucket per key in a ConcurrentHashMap, atomic updates with compute, and eviction for idle keys.
  • "Model an order lifecycle so invalid states cannot exist." Sealed interfaces and records, with exhaustive switches handling transitions.

Many senior Java loops also include a low-level design round. Practice one end to end with our parking lot low-level design walkthrough, and if you are interviewing above senior, the staff engineer interview guide explains how the bar shifts toward architecture and influence.

How to Prepare in Two Weeks

A focused plan beats reading hundreds of questions.

  1. Days 1-3: Core Java and collections. Explain HashMap and ConcurrentHashMap aloud until you can do it in two minutes without notes.
  2. Days 4-6: Concurrency. Write a producer-consumer with BlockingQueue, a virtual thread fan-out, and a deadlock you then fix.
  3. Days 7-8: JVM. Run jcmd against a local app, capture a heap dump, and read a GC log.
  4. Days 9-10: Modern Java. Rewrite one class hierarchy from an old project using sealed interfaces and records.
  5. Days 11-12: Spring Boot. Build a small service with JPA, reproduce the N+1 problem, then fix it. Break @Transactional with self-invocation on purpose.
  6. Days 13-14: Coding rounds in Java. Drill the core problem families from our coding interview patterns cheat sheet and time yourself.

Java loops stack theory, coding, and Spring questions into one long day, and one blank moment on a GC or transaction question can cost the round. TechScreen listens along and shows structured Java answers and code in real time, invisible on Zoom, Google Meet, Teams, HackerRank, and CoderPad. Try it with 3 free tokens, no credit card required.

Get started free →

Frequently Asked Questions

What Java version should I prepare for in a 2026 interview?

Prepare on Java 21 and be aware of Java 25. Both are long-term support releases, and most production teams in 2026 run one of them or are migrating from Java 17. Java 21 finalized virtual threads, record patterns, and pattern matching for switch. Java 25 added the fix for virtual threads pinning inside synchronized blocks and finalized scoped values. Interviewers rarely expect you to know non-LTS releases in detail.

What are the most asked Java interview questions for experienced developers?

Experienced candidates are most often asked how HashMap works internally, how ConcurrentHashMap achieves thread safety, the difference between synchronized and ReentrantLock, how the Java memory model and volatile work, how garbage collectors like G1 and ZGC differ, and how Spring Boot auto-configuration and transactions work. Senior loops add debugging scenarios such as diagnosing a memory leak, a deadlock, or thread pool exhaustion in production.

Are virtual threads asked about in Java interviews?

Yes, increasingly. Virtual threads became a standard feature in Java 21, and Spring Boot supports them with a single property, so backend interviewers now ask when to use them. Expect questions on how they differ from platform threads, why you should not pool them, what pinning is, and why they help I/O-bound services but not CPU-bound work. Knowing that Java 24 and 25 removed most synchronized pinning is a strong signal.

How should I answer how HashMap works internally?

Explain it in layers. HashMap stores entries in an array of buckets. It computes the key's hashCode, spreads the high bits into the low bits, and uses the result to pick a bucket. Collisions go into a linked list that converts to a red-black tree once a bucket holds more than eight entries and the table has at least 64 buckets. The table doubles when size exceeds capacity times the 0.75 load factor.

Do Java interviews still include coding rounds or only theory?

Most Java backend loops include both. A recruiter or phone screen may ask rapid-fire theory questions, but the main loop usually has one or two coding rounds where you solve data structure problems in Java, plus a low-level design or system design round. Theory answers show depth, but you still need to write clean, compiling Java quickly, including correct use of collections, generics, and streams.

How much Spring Boot do I need to know for a Java interview?

For backend roles, enough to explain how a request flows through a Spring Boot application. That means dependency injection and bean scopes, how auto-configuration decides what to create, how @Transactional works through proxies, common JPA pitfalls like the N+1 query problem, and how you configure and observe a service in production. Spring Boot 4.0 shipped in November 2025, so mention it if the team is on the current generation.

Ready to use AI assistance in your next interview?

TechScreen is the invisible AI assistant trusted by engineers interviewing at Google, Meta, Amazon, and hundreds of other companies. Start with 3 free tokens — no credit card required.

Ace your next interview →