Java developer interview questions, from core Java to Spring Boot
Java developer interview questions cover core language rules such as equals and hashCode, the collections framework and how HashMap works inside, concurrency and the Java memory model, JVM memory and garbage collection, Spring Boot and JPA with Hibernate, testing, and features added since Java 8 like streams, records and virtual threads. Most loops pair these with a live coding problem and, for experienced candidates, a design round. Interviewers reward answers that explain why the language behaves as it does, not memorized definitions.
By Evin JohnPublished 9 min read
What Java developers build, and what teams look for
Most Java developers write server-side code: REST and gRPC services in Spring Boot, batch jobs, message consumers on Kafka or RabbitMQ, and the integration code between banks, insurers, retailers and their partners. Some work on Android, big data tooling or trading systems, but the typical job is a long-lived business service with a relational database behind it. That shapes the interview. Teams want people who write readable Java, understand what the JVM does at runtime, and can keep a service fast and correct under concurrent load.
- Language precision: you know the contracts that bite in production, such as equality, immutability and exception handling.
- Concurrency safety: shared state, thread pools and async code that do not deadlock or leak.
- Framework depth: you understand what Spring and Hibernate do for you, and what they do behind your back.
- Runtime awareness: heap sizing, GC behavior, thread dumps and profilers when a service misbehaves.
- Testing habit: unit tests that run fast and integration tests that hit a real database.
How Java interview loops are usually structured
- Recruiter screenJava versions you have used in production, Spring Boot experience, and the kind of systems you worked on.
- Technical phone screenRapid questions on core Java, collections and concurrency, sometimes with a short coding task in a shared editor.
- Coding roundOne or two algorithm or data structure problems in Java, or a practical task such as parsing a file or building a small class hierarchy.
- Framework or take-home roundA small Spring Boot service with a REST endpoint, persistence and tests, or a code review of an existing one.
- Design and behavioralLow-level object design for mid-level roles, system design for senior ones, plus questions on teamwork and incidents.
Core Java questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| You override equals but not hashCode. What breaks? | Object contracts | Equal objects land in different hash buckets, so HashSet and HashMap lookups fail; both methods must use the same fields |
| How do you make a class immutable, and why bother? | Immutability | Final class or private constructor, final fields, no setters, defensive copies of mutable inputs; immutable objects are thread-safe and safe as map keys |
| Why is String immutable, and what is the string pool? | Strings | Security, caching of hash codes and safe sharing; literals are interned so equal literals share one object, which is why == sometimes seems to work |
| When do you pick an interface over an abstract class? | Abstraction | Interfaces for capabilities a class can mix in, with default methods for evolution; abstract classes when subclasses share state or constructor logic |
| Checked or unchecked exceptions: which do you throw from a service method? | Error handling | Unchecked for programming errors and most business failures in modern code, checked where the caller can genuinely recover; never swallow exceptions silently |
| What is type erasure, and how does it limit generics? | Generics | Type parameters are removed at compile time, so you cannot write new T() or check instanceof List<String>; wildcards and bounded types handle variance |
| final, finally and finalize: what is each for? | Keywords | final prevents change or extension, finally runs after try and catch, finalize is deprecated and should be replaced by try-with-resources or Cleaner |
| Is Java pass-by-value or pass-by-reference? | Semantics | Always by value; for objects, the value copied is the reference, so a method can change the object's fields but not which object the caller holds |
Collections framework questions
- How does HashMap store and find entries? An array of buckets indexed by the key's hash. Collisions form a linked list that becomes a balanced tree once a bucket grows large, and the table doubles and rehashes when it passes the load factor.
- ArrayList or LinkedList for a list you mostly read by index? ArrayList. Random access is constant time and memory is contiguous. LinkedList rarely wins in practice, even for inserts, because of cache misses.
- What makes ConcurrentHashMap safe without locking the whole map? Lock-free reads, compare-and-swap and per-bin locking on writes, plus atomic methods like computeIfAbsent and merge so callers avoid check-then-act races.
- What does fail-fast mean for an iterator? Modifying a collection while iterating it, other than through the iterator, throws ConcurrentModificationException. Use removeIf or the iterator's remove method.
- When would you use TreeMap, LinkedHashMap or EnumMap? TreeMap for sorted keys and range queries, LinkedHashMap for insertion or access order (the basis of a simple LRU cache), EnumMap for compact, fast maps keyed by an enum.
- Comparable versus Comparator? Comparable defines a class's natural order; Comparator lets you supply other orders, built neatly with Comparator.comparing and thenComparing.
Concurrency and multithreading questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What does volatile guarantee, and what does it not? | Memory model | Visibility and ordering of reads and writes to that field across threads, but no atomicity for compound actions like count++ |
| Explain happens-before in your own words. | Java memory model | Rules that say when one thread's writes must be visible to another, such as unlocking a monitor before a later lock, or writing a volatile before a later read |
| synchronized or ReentrantLock? | Locking | synchronized is simpler and scoped to a block; ReentrantLock adds tryLock, timeouts, fairness and multiple conditions |
| Why use an ExecutorService instead of new Thread()? | Thread pools | Reuse of threads, bounded queues and back pressure, clean shutdown, and futures for results; size pools by whether work is CPU-bound or blocking |
| How would you call three services in parallel and combine the results? | Async composition | CompletableFuture.supplyAsync on a dedicated executor, allOf or thenCombine, timeouts with orTimeout, and exceptionally for fallbacks |
| What are virtual threads, and when do they help? | Java 21 | Lightweight threads scheduled by the JVM, ideal for high-concurrency blocking I/O; less useful for CPU-heavy work; on Java 21 to 23, blocking inside synchronized pins the carrier thread, which Java 24 largely fixed |
| Two threads lock the same two accounts in opposite order. What happens and how do you prevent it? | Deadlock | Deadlock; always acquire locks in a fixed global order, use tryLock with a timeout, or avoid shared locks with a single-writer design |
| What is ThreadLocal for, and what is its danger in a server? | Thread confinement | Per-thread state such as a request context; with pooled threads values leak between requests unless removed in a finally block |
JVM, memory and garbage collection
- Describe the JVM memory areas. The heap for objects, split by most collectors into young and old generations; a stack per thread for frames and local variables; metaspace for class metadata; and native memory for threads, buffers and the JIT.
- How does generational garbage collection work? Most objects die young, so the young generation is collected often and cheaply, and survivors are promoted to the old generation, which is collected less often.
- G1, ZGC or Parallel: how do you choose? G1 is the general default with pause targets, ZGC and Shenandoah aim for very short pauses on large heaps, and Parallel favors throughput for batch work where pauses matter less.
- A service throws OutOfMemoryError after a few days. How do you investigate? Enable a heap dump on OOM, open it in Eclipse MAT or VisualVM, look at the dominator tree for what retains memory, and check for unbounded caches, static collections or listeners never removed.
- What do you look at when CPU is pegged at 100 percent? Take several thread dumps with jstack or jcmd a few seconds apart, or run async-profiler or Java Flight Recorder, and find the hot methods or busy loops.
- What does the JIT compiler do, and why does it matter for benchmarks? It compiles hot bytecode to optimized machine code at runtime, so first calls are slow; measure with JMH and warm-up, not with a loop and System.nanoTime.
- How does class loading work? Bootstrap, platform and application class loaders with parent delegation; custom loaders appear in app servers and plugins, and are a common source of metaspace leaks.
Spring and Spring Boot questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What problem does dependency injection solve? | IoC | Objects receive their collaborators instead of building them, which makes wiring central and testing with fakes easy; prefer constructor injection |
| What does Spring Boot auto-configuration actually do? | Boot internals | Conditional configuration classes create beans when a library is on the classpath and you have not defined your own, controlled by properties and profiles |
| A @Transactional method calls another @Transactional method in the same class with REQUIRES_NEW. Why is there no new transaction? | Proxies | Transactions are applied by a proxy, and self-invocation bypasses it; move the method to another bean or call through the proxy |
| Which bean scopes exist, and when is a prototype scope a trap? | Bean lifecycle | Singleton by default, prototype, request and session; a prototype injected into a singleton is created only once unless you use a provider or lookup |
| How do you handle errors consistently across REST controllers? | Web layer | A @RestControllerAdvice with exception handlers that map to status codes and a standard error body, such as Problem Details |
| How do you secure a Spring Boot API? | Spring Security | A security filter chain, JWT or OAuth2 resource server configuration, method-level authorization where needed, and no secrets in application properties |
| Which Actuator endpoints would you expose in production? | Operations | Health and metrics for probes and Prometheus, with sensitive endpoints such as env or heapdump disabled or protected |
JPA, Hibernate and data access
- Loading 100 orders also fires 100 queries for their customers. Why, and how do you fix it? Each lazy association is fetched separately. Use a join fetch, an entity graph or batch fetching, and confirm with SQL logging or a test that counts statements.
- What causes LazyInitializationException? Touching a lazy association after the persistence context has closed. Fetch what the view needs inside the transaction, or map to a DTO, rather than turning on open-session-in-view.
- What is the persistence context, and what is dirty checking? The first-level cache of managed entities for a transaction. Hibernate compares their state at flush time and writes changes without an explicit save call.
- How do you stop two users overwriting each other's update? Optimistic locking with a @Version field, which fails the second write so you can retry or report a conflict.
- When would you skip JPA and write SQL directly? Reporting queries, bulk updates and tuned joins, using JdbcTemplate, jOOQ or native queries, while keeping JPA for ordinary entity work.
Java 8 and newer features
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Group a list of employees by department and count them with streams. | Streams API | collect(Collectors.groupingBy(Employee::department, Collectors.counting())), written without looking it up |
| What is the difference between map and flatMap on a stream? | Stream operations | map transforms each element one to one; flatMap turns each element into a stream and flattens the results |
| When should you not use a stream? | Judgment | Simple loops with early exits or checked exceptions, side effects, or hot paths where boxing costs matter; parallel streams only for large CPU-bound work |
| How should Optional be used, and how is it misused? | Optional | As a return type for maybe-absent values; not for fields, parameters or collections, and never by calling get without a check |
| What do records and sealed classes give you? | Java 16 and 17 | Records are concise immutable data carriers with equals, hashCode and toString; sealed hierarchies list their permitted subtypes so the compiler can check them |
| Show a switch with pattern matching over a sealed type. | Java 21 | A switch expression that matches each permitted record type, with no default branch needed because the compiler knows the cases are exhaustive |
class LruCache<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
LruCache(int capacity) {
super(16, 0.75f, true); // access order, not insertion order
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}Be ready to explain why the third constructor argument matters, why this version is not thread-safe, and how you would build the same cache from a HashMap plus a doubly linked list if the interviewer forbids LinkedHashMap.
Testing, coding and design rounds
- How do you test a service class that calls a repository and an external API? JUnit 5 with Mockito for the collaborators, AssertJ for readable assertions, and one focused test per behavior, including failure paths.
- @SpringBootTest or a slice test such as @WebMvcTest or @DataJpaTest? Slices for speed and focus, the full context only for a few end-to-end checks. Testcontainers gives integration tests a real Postgres or Kafka instead of an in-memory stand-in.
- What does a typical coding round look like? Arrays, strings, hash maps, two pointers, trees, BFS and DFS, and heaps via PriorityQueue. Write idiomatic Java with clear names, and state the time and space complexity aloud.
- Design classes for a parking garage, an elevator or a library system. Interviewers watch for clear responsibilities, interfaces for behavior that varies, sensible use of enums and records, and SOLID ideas applied without ceremony.
- Senior design prompt: an order service that must not lose or double-charge an order. Talk about idempotency keys, transactions and the outbox pattern, retries with backoff and how you would observe it.
- How do you review a teammate's pull request? Correctness and tests first, then concurrency and resource handling, then naming and structure. Explain the why behind each comment.
Fictional example
- Our pricing service started timing out every afternoon at peak. Dashboards showed p99 latency jumping from about 200 milliseconds to several seconds, with GC pauses rising at the same time. I took a heap dump during the spike and saw a ConcurrentHashMap used as a cache holding millions of entries, because the key included a timestamp and nothing ever expired. Every request added more, the old generation filled, and the collector ran almost constantly. I replaced it with a Caffeine cache with a size limit and a ten-minute expiry, fixed the key to exclude the timestamp, and added cache hit rate and heap usage to our Grafana dashboard. The afternoon spikes stopped, and we added a code review check for unbounded maps used as caches.
Java roles are usually backend roles, so the backend developer interview guide is worth a pass for API and database design. Teams that use Python alongside Java often borrow from the Python developer interview guide as well.
Questions to ask the team
- Which Java version runs in production, and how do you plan upgrades?
- Is the codebase mostly Spring Boot microservices, a modular monolith or something older?
- How are services tested before they reach production, and how long does the build take?
- Who is on call for the services this team owns?
Ten days of Java interview practice
- Days 1 to 2: core and collectionsRewrite equals, hashCode and an immutable value class from memory. Explain HashMap resizing on paper.
- Days 3 to 4: concurrencyBuild a producer-consumer with a BlockingQueue, compose three CompletableFutures, then try the same with virtual threads.
- Days 5 to 6: Spring BootBuild a small CRUD service with JPA, validation, error handling and Testcontainers tests. Reproduce an N+1 query and fix it.
- Days 7 to 8: coding problemsTwo or three problems a day in Java, timed, talking through your approach aloud.
- Days 9 to 10: JVM and storiesRead a GC log and a thread dump, then prepare stories about a production bug, a performance fix, a disagreement and a release.
Natively, an AI interview assistant for Mac and Windows, makes mock Java rounds easier to review. It transcribes the practice session on your computer, can suggest an answer while a question about the memory model or Spring proxies is still on the table, and can read a coding prompt from a screenshot. With Pro or the free trial, your résumé and the job description shape those suggestions around your own services. Afterward, the saved transcript and notes show which explanations wandered.
Questions people ask
What are the most common Java developer interview questions?
The equals and hashCode contract, how HashMap works, String immutability, checked versus unchecked exceptions, volatile versus synchronized, thread pools and CompletableFuture, garbage collection, Spring dependency injection and @Transactional, and the N+1 problem in Hibernate.
What Java interview questions should experienced developers expect?
Deeper concurrency and the memory model, diagnosing memory leaks and GC pauses, Spring proxy behavior, JPA performance, virtual threads and other Java 21 features, and a system design round about a service you would build.
Which Java version should I prepare for?
Know Java 8 streams and lambdas well, then the main additions in 11, 17 and 21: var, records, sealed classes, pattern matching for switch, text blocks and virtual threads. Ask the recruiter which version the team runs.
Do Java interviews include coding problems?
Nearly always. Expect one or two data structure or algorithm problems written in Java, and sometimes a take-home Spring Boot service or a code review exercise.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
