GUIDE INTERVIEW QUESTIONS

Java developer interview questions

Evaluate Java developers through realistic questions, practical exercises, and evidence-based scoring. This guide covers language fundamentals, concurrency, Spring, persistence, testing, and production judgment.

What Java developer interview questions should reveal

The best java developer interview questions reveal how candidates reason about application behavior, not just whether they remember language terminology. For hiring managers, technical leads, and interviewers, the objective is to distinguish developers who can explain a concept from those who can apply it safely in a production Java service.

A useful interview connects language knowledge to observable outcomes: correct collection behavior, predictable transaction boundaries, controlled concurrency, meaningful tests, and effective incident diagnosis. It should also reflect your actual environment. Maintaining a Java 8 application server requires different preparation from building Spring Boot services on Java 21 or Java 25.

This MyDiscussions guide organizes questions around those signals, with evaluation criteria, follow-up prompts, and a practical interview process.

Define the role before choosing questions

Start with the work the developer will own. A backend engineer integrating PostgreSQL and Kafka needs a different assessment from someone building low-latency infrastructure or Android applications.

Record these requirements before writing the interview:

  • Runtime and language: Production JDK version, upgrade plans, and use of features such as records, sealed classes, or virtual threads.
  • Application stack: Spring Boot, Jakarta EE, Quarkus, Micronaut, or framework-light Java.
  • Data responsibilities: SQL, JPA/Hibernate, transaction management, caching, and messaging.
  • Operational ownership: Deployment, observability, performance investigation, and on-call duties.
  • Expected autonomy: Implementing scoped tasks versus defining architecture and handling ambiguous failures.

Avoid treating every technology in the job description as equally important. Classify skills as required on entry, learnable during onboarding, or specialist depth.

Calibrate expectations by seniority

LevelExpected evidenceSuitable question depth
JuniorCorrect fundamentals, readable code, basic tests, willingness to clarify assumptionsCollections, exceptions, simple SQL, straightforward debugging
Mid-levelIndependent feature delivery, transaction awareness, practical framework knowledgeAPI design, concurrency hazards, persistence behavior, integration tests
SeniorExplicit trade-offs, failure analysis, operational judgment, architectural boundariesConsistency, overload control, migrations, production diagnosis

Seniority should change the depth of follow-up questions, not merely increase the number of obscure topics.

Core Java questions that expose real understanding

1. How do equals() and hashCode() affect a HashMap?

Ask the candidate to explain what happens when an object used as a map key changes after insertion.

Strong answers identify:

  • Equal objects must have equal hash codes; equal hash codes do not prove equality.
  • Hash-based collections use hashing and equality checks to locate entries.
  • Mutating fields involved in equality or hashing can make an existing entry effectively unreachable through normal lookup.
  • Immutable keys simplify reasoning.

A useful follow-up is: “Would a record automatically make this key safe?” Records provide generated equality and hashing, but their components can reference mutable objects. The candidate should distinguish shallow immutability from deep immutability.

Weak signal: Reciting the contract without explaining a lookup failure.

2. When would you choose ArrayList, HashSet, or TreeMap?

Give a concrete requirement: store unique customer identifiers, preserve sorted lookup, or process an ordered batch.

Look for decisions based on:

  • Duplicate handling and ordering requirements.
  • Typical lookup, insertion, and traversal costs.
  • Memory allocation and locality.
  • Thread-safety requirements.

A strong candidate avoids statements such as “linked lists are always faster for insertion.” Locating the insertion position and allocation overhead matter. Ask whether the collection is small enough that simpler code matters more than asymptotic differences.

3. How should exceptions cross an application boundary?

Present a REST endpoint that calls a repository and an external payment provider.

The candidate should separate validation errors, business conflicts, dependency failures, and programming defects. Good answers preserve useful causes, avoid leaking sensitive internals, and map failures to appropriate API responses.

Ask when retries are safe. “Retry every exception” is a warning sign: retries can duplicate side effects and amplify overload. Strong answers discuss transient failures, idempotency, timeouts, and bounded retry policies.

Concurrency and JVM questions

4. What does volatile guarantee, and what does it not guarantee?

Use a shared counter as the example. A volatile field provides visibility and ordering guarantees, but count++ remains a compound read-modify-write operation.

Candidates should explain when to use:

  • AtomicInteger for atomic updates to one value.
  • Locks or synchronization for invariants spanning multiple operations.
  • Thread confinement or immutable data to avoid shared mutation.

For senior roles, ask why making every field volatile does not make an object thread-safe. The key signal is reasoning about invariants and happens-before relationships, not memorizing terminology. The Java Language Specification’s concurrency rules provide an authoritative reference for evaluating disputed claims.

5. Would virtual threads improve this service?

Describe a service that spends most request time waiting for HTTP and database responses.

Strong answers explain that virtual threads can improve concurrency for blocking, I/O-heavy workloads, but do not make CPU-bound work execute faster. Candidates should still consider database connection limits, downstream capacity, cancellation, and deadlines.

Ask what happens if thousands of requests compete for a small connection pool. Virtual threads do not remove the bottleneck; admission control and bounded resource usage still matter.

For deeper discussion, distinguish concurrency from parallelism and ask how the team would verify throughput and latency improvements. Runtime-specific caveats should be evaluated against the target JDK rather than treated as timeless rules.

6. How would you investigate rising latency and heap usage?

Provide symptoms instead of asking for definitions of garbage collectors.

A practical investigation should include:

  • Checking recent deployments and changes in traffic.
  • Separating CPU saturation, lock contention, allocation pressure, and downstream waits.
  • Inspecting metrics, traces, garbage-collection logs, and thread behavior.
  • Using Java Flight Recorder and Java Mission Control when appropriate.
  • Taking heap dumps cautiously because of operational cost and potentially sensitive contents.

Strong candidates form hypotheses before tuning heap sizes or switching collectors. For example, retained cache entries suggest a different investigation from high allocation rates with stable retained memory.

Spring and persistence questions

7. When might @Transactional not behave as expected?

For a Spring role, ask about one method calling another method on the same object.

In the usual proxy-based configuration, self-invocation bypasses the proxy, so the called method’s transactional annotation does not independently establish the expected boundary. Candidates should clarify configuration rather than claim annotations always work identically.

Follow up with rollback behavior. By default, Spring rolls back for unchecked exceptions and Error, not every checked exception; applications can configure other rules.

The best answers connect this to service boundaries, transaction duration, and integration tests. Use the Spring Framework transaction documentation to ground version- and configuration-sensitive discussions.

8. How would you diagnose an N+1 query problem?

Describe a page listing orders and their line items that becomes slower as the result size increases.

Look for:

  • Inspection of SQL logs, query counts, or database traces.
  • Recognition that relationship loading can trigger additional queries.
  • Consideration of fetch joins, entity graphs, batching, or DTO projections.
  • Awareness that fetching too much data creates its own performance problems.

A strong candidate discusses pagination complications when fetching collection relationships. “Make everything eager” is not a robust fix.

Ask how they would prove the improvement. Useful evidence includes representative datasets, query counts, execution plans, and endpoint latency—not just a faster local demonstration.

9. How would you coordinate a database update and a Kafka event?

Present an order update that must also publish an event.

The candidate should recognize the dual-write problem: committing the database and publishing the message are separate operations unless an appropriate coordination mechanism exists.

For senior backend roles, expect discussion of the transactional outbox pattern, delivery retries, duplicate processing, and consumer idempotency. Kafka transactions alone do not automatically make an unrelated relational database commit atomic.

Accept different architectures when candidates explain the guarantees, failure modes, and operational costs.

Testing and coding exercises

10. What should be mocked, and what needs an integration test?

Ask candidates to design tests for a Spring service that stores an order and calls a shipping API.

Good answers distinguish:

  • Unit tests: Business decisions, edge cases, and deterministic transformations.
  • Integration tests: SQL behavior, mappings, migrations, transaction boundaries, and framework wiring.
  • Contract tests: Assumptions at service boundaries.
  • End-to-end tests: A limited set of critical user journeys.

JUnit and Mockito are useful for focused tests. Testcontainers can exercise a real PostgreSQL instance rather than relying exclusively on an in-memory substitute with different behavior.

Candidates should acknowledge the trade-off: realistic integration tests catch more infrastructure-specific failures but cost more startup time and maintenance. The Testcontainers for Java documentation explains its disposable dependency model.

A practical exercise: implement an idempotent reservation operation

Ask the candidate to implement or review a reservation service accepting a customer identifier, SKU, quantity, and idempotency key.

Keep the live exercise scoped. Supply a project skeleton, interfaces, and existing tests rather than spending the session fixing Maven configuration.

Evaluate whether the candidate:

  • Clarifies what repeated requests should return.
  • Rejects invalid quantities and missing identifiers.
  • Separates business rules from transport concerns.
  • Handles insufficient stock.
  • Writes tests for repeated requests and boundary conditions.
  • Recognizes that an in-memory check-then-write sequence is unsafe across concurrent requests or multiple instances.

For junior candidates, use an in-memory implementation and discuss limitations. For senior candidates, explore database constraints, atomic updates, and conflicting payloads using the same idempotency key.

A step-by-step interview process

Step 1: Build a competency map

Choose four to six competencies tied to the job. For a Spring backend role, these might be Java correctness, persistence, testing, concurrency, and production diagnosis.

Mark which are mandatory. Excellent JVM trivia should not compensate for unsafe transaction reasoning when transaction ownership is central to the role.

Step 2: Standardize the core prompts

Give candidates for the same role equivalent questions, time, and available tools. Prepare follow-ups in advance and document acceptable alternative approaches.

State whether documentation, IDE assistance, or AI tools are allowed. If AI assistance is permitted, assess verification and explanation rather than assuming generated code demonstrates understanding.

Step 3: Run a balanced technical session

A practical session might allocate:

  • A short opening to establish project context and assumptions.
  • A focused discussion of Java and stack-specific scenarios.
  • A coding or code-review exercise.
  • A closing discussion of testing, failure modes, and trade-offs.

Do not squeeze every question in this guide into one interview. Select a representative subset and investigate reasoning deeply.

Step 4: Score evidence independently

Use an anchored rubric before interviewer discussion.

ScoreEvidence anchor
1 — InsufficientCannot explain the central behavior or proposes an unsafe solution without recognizing the risk
2 — DevelopingIdentifies part of the problem but needs substantial prompting
3 — Meets expectationsProduces a sound approach, explains limitations, and validates key assumptions
4 — StrongAnticipates important failures and compares alternatives with clear operational reasoning

Record what the candidate actually said or implemented. Separate “not assessed” from “failed.”

Step 5: Debrief against role requirements

Discuss disagreements using concrete observations. Decide whether gaps concern essential skills or teachable framework details. Avoid averaging away a critical correctness problem with unrelated strengths.

Common mistakes when interviewing Java developers

  • Testing outdated trivia: Finalizer trivia rarely predicts service delivery. Legacy topics are appropriate when the role actually involves them.
  • Confusing framework recall with competence: Remembering an annotation name is weaker evidence than explaining proxy behavior and testing it.
  • Rewarding one preferred architecture: A modular monolith may be more appropriate than microservices. Evaluate the stated constraints.
  • Ignoring runtime versions: Language features, APIs, and performance characteristics change across JDK releases.
  • Using puzzles as the entire assessment: Algorithm exercises alone miss transactions, observability, and maintainability.
  • Penalizing clarification: Questions about ordering, consistency, and retry semantics often indicate sound engineering judgment.
  • Overvaluing polished speech: Assess technical evidence separately from presentation style.

Frequently asked questions

Which Java developer interview questions are best for junior candidates?

Prioritize equality, collections, exceptions, simple object design, and basic testing. Use small examples where candidates can predict behavior and correct mistakes. Advanced garbage-collector tuning or distributed transaction design should not be default entry-level requirements.

Should every Java interview include Spring Boot questions?

No. Include Spring questions when the role uses Spring or requires immediate familiarity. For other environments, test equivalent concerns—dependency management, request handling, transactions, and configuration—through the relevant framework or plain Java scenarios.

How much coding should a Java interview include?

Include enough implementation or code review to observe correctness, decomposition, and testing. A focused exercise is more useful than several rushed puzzles. For senior roles, supplement coding with architectural and operational questions rather than replacing hands-on evidence entirely.

How can interviewers assess unfamiliar but valid solutions?

Ask the candidate to explain assumptions, failure modes, and verification steps. Check disputed details against official documentation after the session. Score demonstrated reasoning separately from unresolved API facts, and avoid rejecting an approach simply because it differs from the interviewer’s usual implementation.

For related role-specific evaluation guides, browse more Interview questions topics.

Have a question about this topic?

Ask the community and get answers from practitioners.

Start a discussion