Interview questions · Tech stack

Java (10 Years Experience) Interview Questions & Answers (2026)

These interviews test deep mastery of Java language internals, concurrency, JVM tuning, design patterns, and ecosystem tools. A strong candidate demonstrates clear reasoning, trade‑off analysis, and real‑world examples. Focus on explaining why a solution works, its performance impact, and how it fits into maintainable architecture to succeed.

20 questions · updated Aug 29, 2026

Quick facts

Typical roundsPhone screen, coding challenge, system design, deep dive on concurrency and JVM
Key focus areasConcurrency, memory management, design patterns, microservices, performance profiling
Preferred experience10+ years Java, Spring ecosystem, cloud deployments, CI/CD pipelines
Common formatsLive coding on IDE, whiteboard design, take‑home project

Questions

Beginner

Explain the difference between synchronized and ReentrantLock. When would you choose one over the other?

Synchronized is a language keyword that provides intrinsic locking with built‑in monitor exit on exception and supports reentrancy automatically. ReentrantLock is a java.util.concurrent class offering explicit lock control, tryLock, timed lock acquisition, and condition variables. Choose synchronized for simple mutual exclusion and readability; choose ReentrantLock when you need non‑blocking attempts, fairness policies, or multiple condition objects. Interviewers look for awareness of lock granularity, deadlock avoidance, and performance implications of lock contention.

Lock lock = new ReentrantLock();
lock.lock();
try { /* critical section */ } finally { lock.unlock(); }
GoogleAmazonMicrosoft

What is the Java Memory Model and why does it matter for multithreaded code?

The Java Memory Model (JMM) defines how threads interact through memory, specifying visibility guarantees, ordering rules, and atomicity of operations. It matters because without proper synchronization, writes by one thread may not become visible to another, leading to stale data or reordering bugs. Understanding JMM lets a candidate explain volatile, final, and happens‑before relationships, and why lock‑based or atomic constructs are required for safe concurrency.

NetflixLinkedIn

What is the difference between @Component, @Service, and @Repository in Spring?

@Component is a generic stereotype for any Spring-managed bean. @Service indicates a service‑layer component, adding semantic clarity and enabling future AOP extensions. @Repository marks a data‑access component, translating persistence exceptions into Spring’s DataAccessException hierarchy. Interviewers expect you to explain bean scanning, the role of each annotation, and why semantic distinction aids readability and tooling.

AmazonIBM

How does Java's volatile keyword differ from atomic classes like AtomicInteger?

Volatile guarantees visibility of writes to other threads and prevents reordering, but does not provide atomic read‑modify‑write operations. AtomicInteger offers atomic methods like incrementAndGet, ensuring thread‑safe updates without explicit synchronization. Interviewers look for explanation of the ABA problem, why volatile alone can't safely increment a counter, and when to choose atomic classes over synchronized blocks.

CiscoIntel

What are the main advantages of using records introduced in Java 16?

Records provide a concise syntax for immutable data carriers, automatically generating constructors, accessors, equals, hashCode, and toString. They reduce boilerplate, improve readability, and enforce immutability by default. Candidates should mention that records are final, cannot extend other classes, and are ideal for DTOs, configuration objects, and pattern matching scenarios.

DropboxAtlassian

How does the Java 11 HttpClient differ from the older HttpURLConnection?

HttpClient is non‑blocking, supports HTTP/2, provides a fluent API, and allows asynchronous request handling via CompletableFuture. HttpURLConnection is blocking, limited to HTTP/1.1, and has a cumbersome API. Interviewers expect you to mention features like connection pooling, request/response body publishers, and built‑in timeout handling, highlighting why HttpClient is preferred for modern microservices.

GoogleMicrosoft

Intermediate

Describe how the garbage collector works in Java 17. Which collector would you pick for a low‑latency service?

Java 17 includes several collectors: Serial, Parallel, G1, ZGC, and Shenandoah. They differ in pause times, throughput, and heap handling. For low‑latency services, ZGC or Shenandoah are preferred because they perform most work concurrently, yielding sub‑millisecond pause times. The answer should cover generational collection, young vs. old generation, and why a concurrent collector reduces stop‑the‑world pauses, while also noting trade‑offs like higher CPU usage.

java -XX:+UseZGC -Xmx8g -Xms8g MyApp
TwitterUber

How does the fork/join framework improve parallelism compared to traditional thread pools?

ForkJoinPool recursively splits tasks into subtasks, allowing work‑stealing where idle threads execute tasks from other workers' queues. This reduces contention and improves load balancing for divide‑and‑conquer algorithms. Traditional thread pools use a fixed queue, which can cause bottlenecks when tasks vary in size. Interviewers expect you to discuss RecursiveTask vs. RecursiveAction, work‑stealing benefits, and when to prefer ForkJoin over ExecutorService.

ForkJoinPool pool = new ForkJoinPool();
Long sum = pool.invoke(new SumTask(arr, 0, arr.length));
AirbnbDropbox

What are the main differences between HashMap and ConcurrentHashMap?

HashMap is not thread‑safe; concurrent modifications cause undefined behavior. ConcurrentHashMap provides thread safety with fine‑grained locking (segment or bin-level) and lock‑free reads, allowing high concurrency. It also disallows null keys/values and offers atomic bulk operations like computeIfAbsent. Candidates should discuss performance impact, consistency guarantees, and why ConcurrentHashMap is preferred for shared mutable state in multi‑threaded environments.

PayPaleBay

Describe how you would profile a Java application to find a CPU hotspot.

Use a sampling profiler like async-profiler or Java Flight Recorder (JFR) to capture stack traces at intervals, then analyze the flame graph to locate methods with highest CPU consumption. Complement with JVisualVM for thread dumps and GC analysis. A good answer includes steps: enable JFR, run workload, generate recording, open in JMC, identify hot methods, and propose optimizations such as algorithmic changes or caching.

java -XX:StartFlightRecording=duration=60s,filename=record.jfr -jar app.jar
OracleAdobe

Explain the trade‑offs between eager and lazy initialization of singleton beans in Spring.

Eager initialization creates beans at container startup, ensuring early failure detection and simplifying dependency graphs, but increases startup time and memory usage. Lazy initialization defers bean creation until first use, reducing startup cost and allowing optional beans, but may hide configuration errors until runtime. Interviewers expect you to discuss @Lazy, bean scopes, and when to apply each strategy in microservice vs. monolith contexts.

ShopifyTwitter

What is the difference between @Transactional(propagation = Propagation.REQUIRES_NEW) and Propagation.MANDATORY?

REQUIRES_NEW always starts a new transaction, suspending any existing one, ensuring independent commit/rollback. MANDATORY requires an existing transaction; if none exists, an exception is thrown. The answer should cover use cases: REQUIRES_NEW for audit logs needing separate commit, MANDATORY for enforcing caller‑provided transaction boundaries, and the impact on rollback behavior.

GoldmanSachsJPMorgan

What is the purpose of the @JsonIdentityInfo annotation in Jackson, and when would you use it?

@JsonIdentityInfo adds object identity handling to prevent infinite recursion in bi‑directional relationships by using an identifier field. It is used when serializing entities with circular references, such as parent‑child graphs, to avoid StackOverflowError. The answer should cover how it replaces @JsonManagedReference/@JsonBackReference, the impact on deserialization, and typical use in JPA entities.

NetflixShopify

Advanced

Explain the concept of back‑pressure in reactive streams and how Project Reactor handles it.

Back‑pressure is a mechanism where downstream subscribers signal demand to upstream publishers, preventing overwhelming buffers. Project Reactor implements this via the Publisher‑Subscriber contract, using request(n) to control the number of emitted items. Operators respect demand, buffering or dropping excess based on strategies like onBackpressureBuffer or onBackpressureDrop. Interviewers look for understanding of non‑blocking flow control, the difference between hot and cold sources, and how back‑pressure impacts system stability.

Flux.range(1, 1000)
    .onBackpressureBuffer(100)
    .subscribe(System.out::println);
NetflixShopify

How does the Java 8 Stream API achieve lazy evaluation, and why is it important?

Streams are built on a pipeline of intermediate operations that are not executed until a terminal operation triggers evaluation. Each intermediate step creates a new stage but does not process elements immediately; instead, elements flow through the pipeline on demand. Lazy evaluation enables short‑circuiting, reduces memory usage, and allows parallel execution without materializing intermediate collections. A strong answer mentions spliterator, pipeline fusion, and the benefit of composability.

List<Integer> result = list.stream()
    .filter(x -> x > 10)
    .map(x -> x * 2)
    .collect(Collectors.toList());
GoogleMicrosoft

What are sealed classes in Java 17 and how do they improve API design?

Sealed classes restrict which other classes or interfaces may extend or implement them, using the permits clause. This enables exhaustive pattern matching in switch expressions and provides compile‑time safety for hierarchies. By limiting subclassing, APIs can guarantee invariants and reduce unexpected extensions, improving maintainability. Interviewers look for examples like a Shape hierarchy where only Circle, Rectangle, and Triangle are allowed.

public sealed interface Shape permits Circle, Rectangle, Triangle {}
SpotifySquare

How does the Java classloader delegation model work, and when might you break it?

The delegation model follows parent‑first loading: a classloader first asks its parent to load a class before attempting itself. This prevents duplicate definitions and ensures core Java classes are loaded by the bootstrap loader. Breaking it (child‑first) is useful in plugin architectures or application servers to isolate versions of libraries. Candidates should discuss security implications, how to implement a custom loader, and typical use cases like OSGi.

RedHatVMware

Explain how the Java module system (JPMS) enhances encapsulation.

JPMS introduces explicit module declarations (module-info.java) that define required modules and exported packages. It enforces strong encapsulation at compile and runtime, preventing accidental use of internal APIs. By declaring exports and opens, developers control which packages are accessible, reducing classpath conflicts and enabling reliable modular builds. Interviewers expect discussion of readability, service loader usage, and migration challenges.

OracleIBM

What is the difference between a warm‑up phase and a steady‑state phase in JMH benchmarks?

Warm‑up allows the JVM to perform JIT compilation, class loading, and optimizations, ensuring measurements reflect steady‑state performance. The steady‑state phase collects actual timing data after warm‑up. Interviewers look for understanding that without warm‑up, results are skewed by interpreter overhead, and that proper benchmarking isolates these phases to produce reliable metrics.

OracleAmazon

Describe how you would implement a thread‑safe LRU cache in Java.

Use a LinkedHashMap with accessOrder=true and override removeEldestEntry to enforce size, then wrap it with Collections.synchronizedMap or use ConcurrentHashMap with a separate doubly‑linked list protected by a ReentrantLock. Explain trade‑offs: synchronized map is simple but blocks all accesses; lock‑striped approach improves concurrency. Mention handling of null values and eviction callbacks as additional robustness.

class LRUCache<K,V> extends LinkedHashMap<K,V> {
    private final int max;
    LRUCache(int max){ super(max,0.75f,true); this.max=max; }
    protected boolean removeEldestEntry(Map.Entry<K,V> e){ return size()>max; }
}
UberAirbnb

Common mistakes

  • Using synchronized for high‑contention locks instead of ReentrantLock with tryLock
  • Assuming volatile provides atomic increments, leading to race conditions
  • Neglecting to profile before optimizing, resulting in premature optimization
  • Choosing the wrong garbage collector for latency‑sensitive services
  • Overusing eager bean initialization causing slow startup times

Study plan

  1. Review core Java concurrency primitives and JMM fundamentals
  2. Deep‑dive into JVM internals, GC algorithms, and profiling tools
  3. Practice design pattern implementations and trade‑off discussions
  4. Solve coding problems focusing on streams, collections, and algorithms
  5. Mock system‑design interviews emphasizing microservice architecture and performance

FAQ

How many interview rounds are typical for senior Java roles?

Most companies use 4–5 rounds: an initial phone screen, a coding challenge, a deep‑dive technical interview, a system‑design session, and a cultural fit interview.

Should I focus on Java 8 features or newer releases?

Cover both. Java 8 fundamentals are still expected, but many firms now run on Java 11‑17 and ask about records, sealed classes, and modern HttpClient usage.

Is it necessary to know Spring Boot for senior Java positions?

Yes. Spring Boot is the de‑facto framework for building microservices; expect questions on dependency injection, bean scopes, and actuator health checks.

What level of algorithmic difficulty is typical?

Expect medium‑hard problems such as graph traversal, concurrency puzzles, and performance‑critical coding tasks that can be solved in 30–45 minutes.

How important is knowledge of cloud platforms?

Very important. Senior roles often involve deploying Java services to AWS, Azure, or GCP, so be ready to discuss containerization, CI/CD pipelines, and cloud‑native patterns.

Related

Ready for your next interview?

Download MiPrep AI. Load your resume and the job description. Show up ready.

Free tier · No credit card · macOS 14+ · Windows 10+

Free tier · No credit card · Runs on your Mac or Windows machine