OctogleHire
← Interview questions library

25 Java interview questions

Structure the Java interview loop so each stage tests a different signal. Start with a short recruiter or hiring-manager screen to confirm role fit, remote collaboration, and recent Java exposure. Follow with a technical screen focused on reasoning: reading code, diagnosing failures, explaining trade-offs in Java 21/25, Spring Boot 3, persistence, and concurrency. Use a practical exercise to see how the candidate structures code, tests behavior, and handles edge cases without hand-waving. Add a system design round for service boundaries, data consistency, observability, deployment, and JVM operations. For senior and lead candidates, include a cross-functional round on mentoring, technical decision-making, incident response, and aligning engineering work with product constraints.

Junior Java questions

Fundamentals, learning speed and how they debug.

  1. 01You are reviewing a small Java service where a method sometimes returns an empty list even though the database has rows. How would you debug it?

    Listen for: A strong answer starts by reproducing the issue with known inputs, checking logs and query parameters, then narrowing layers: controller, service, repository, transaction boundaries, and mapping. They should mention adding focused tests, verifying environment data, and avoiding random code changes before understanding whether the issue is query logic, filtering, or serialization.

    Red flag: They immediately blame the database or framework without describing a reproducible debugging path.

  2. 02When would you use a record instead of a class in modern Java, and when would you avoid it?

    Listen for: Listen for practical judgment: records are good for immutable data carriers, DTOs, value-like objects, and pattern matching use cases. They should know records have generated accessors and value-based equality, but avoid them when mutable state, complex invariants, inheritance, JPA entities, or behavior-heavy domain models are needed.

    Red flag: They describe records as just shorter POJOs and ignore immutability and framework implications.

  3. 03A REST endpoint accepts a request body, calls another service, and writes to a database. Where would you put validation, and what would you test?

    Listen for: They should separate input validation at the API boundary from business validation in the service/domain layer. Good signals include Bean Validation, explicit error responses, testing invalid payloads, business rule failures, persistence side effects, and downstream-service failures. They should not rely only on controller tests or only on happy-path examples.

    Red flag: They put all validation in the controller or only trust frontend validation.

  4. 04Explain a time you would choose Optional, and a time you would not use it.

    Listen for: A good answer uses Optional for return values where absence is expected, especially from lookup methods. They should avoid Optional for fields, method parameters, collection elements, or serialization models unless there is a clear reason. Listen for null-handling strategy, readable call sites, and not chaining Optional to hide poor domain modeling.

    Red flag: They use Optional everywhere or say it eliminates all NullPointerExceptions.

  5. 05You see a unit test that sleeps for two seconds before asserting a result. What concerns do you have, and how would you improve it?

    Listen for: They should identify flakiness, slow feedback, race conditions, and environment sensitivity. Strong candidates propose deterministic synchronization, fake clocks, Awaitility with bounded waits, mocks or test doubles for async dependencies, and designing code so time and threading behavior can be controlled in tests.

    Red flag: They accept fixed sleeps as normal or simply increase the timeout.

  6. 06How would you handle an exception thrown by a dependency in a Spring Boot service method?

    Listen for: Look for context-aware handling: catch only exceptions they can translate or recover from, preserve cause and useful context, avoid swallowing errors, map expected failures to domain exceptions or HTTP responses, and let unexpected failures surface. They should mention logging once at the boundary and testing failure paths.

    Red flag: They catch Exception broadly, log it, and return null or an empty response.

Mid-level Java questions

Independent delivery, trade-offs and code quality.

  1. 07A Spring Boot 3 API has gradually become slower. What would you check before changing code?

    Listen for: Strong candidates gather evidence first: request metrics, logs with correlation IDs, database query timings, thread dumps, connection pool usage, GC behavior, and external dependency latency. They should compare recent deploys, traffic shape, and data growth, then form hypotheses. Listen for Micrometer, OpenTelemetry, Actuator, and careful rollback or feature-flag thinking.

    Red flag: They suggest rewriting the endpoint or adding caching before identifying the bottleneck.

  2. 08How do you decide transaction boundaries in a service that updates several tables and publishes an event?

    Listen for: They should discuss business consistency, aggregate boundaries, database transaction scope, isolation, retries, and avoiding long transactions around remote calls. Good answers mention the transactional outbox pattern, idempotent consumers, commit-before-publish hazards, and using Spring @Transactional carefully with proxy limitations and checked exception behavior.

    Red flag: They publish to Kafka or another broker inside the database transaction and assume both will commit atomically.

  3. 09You need to add caching to a read-heavy Java service. What trade-offs do you consider?

    Listen for: Listen for cache key design, invalidation strategy, TTLs, consistency requirements, cache stampede prevention, memory limits, observability, and fallback behavior. They should distinguish local caches like Caffeine from distributed caches like Redis, and explain how they would test correctness under stale data and concurrent requests.

    Red flag: They describe caching as a simple annotation with no discussion of invalidation or failure modes.

  4. 10How would you migrate a Java 11 Spring service to Java 21 or 25?

    Listen for: A strong answer covers dependency and plugin compatibility, Spring Boot version requirements, CI images, container base images, JVM flags, deprecated APIs, reflection/module issues, performance baselines, and staged rollout. They may mention virtual threads as an evaluation, not an automatic change, and keeping behavior stable before adopting new language features.

    Red flag: They focus only on changing the language level in the build file.

  5. 11A production incident shows many blocked request threads. How would you investigate in a Java application?

    Listen for: They should describe collecting thread dumps, checking lock contention, connection pool exhaustion, slow downstream calls, synchronized blocks, and servlet container thread usage. Good answers mention JFR, async-profiler, Actuator, Kubernetes events, and correlating blocked threads with request traces before deciding whether to tune pools or fix code.

    Red flag: They immediately increase the thread pool size without identifying why threads are blocked.

  6. 12How do you structure tests for a Spring Boot service that uses JPA and calls an external HTTP API?

    Listen for: Look for a test pyramid with fast unit tests for business logic, slice tests for repositories or controllers, integration tests using Testcontainers for the database, and WireMock or MockWebServer for HTTP dependencies. They should avoid overusing full @SpringBootTest and should test transactions, mappings, and failure responses.

    Red flag: They mock every dependency, including JPA behavior, and never run against a real database.

  7. 13You are asked to refactor a large service class with many private methods. How would you approach it safely?

    Listen for: A good answer starts with characterization tests around observable behavior, not testing private methods directly. They should identify responsibilities, extract cohesive collaborators, improve names and seams, and make small commits. Listen for preserving transactional behavior, security checks, logging context, and avoiding a rewrite disguised as refactoring.

    Red flag: They split the class mechanically by method count without understanding responsibilities or behavior.

Senior Java questions

Judgement, architecture and raising the team's bar.

  1. 14A team wants to use virtual threads for a high-throughput Spring Boot API. How would you evaluate that decision?

    Listen for: Strong candidates explain that virtual threads help blocking I/O workloads but do not make CPU-bound work faster. They should check JDBC driver behavior, connection pool limits, synchronized bottlenecks, ThreadLocal usage, observability, load tests, and failure behavior. They should compare against reactive or traditional servlet models based on team skill and operational complexity.

    Red flag: They treat virtual threads as a universal performance fix and ignore database or downstream limits.

  2. 15How would you design idempotency for a payment-like operation in a Java service?

    Listen for: Listen for client-supplied idempotency keys, uniqueness constraints, request fingerprinting, persisted operation state, safe retries, and clear response semantics for in-progress, succeeded, and failed operations. They should address transaction boundaries, race conditions, replay windows, observability, and not relying only on in-memory locks.

    Red flag: They say retries are safe because the endpoint checks whether a record already exists.

  3. 16You inherit a monolith with slow delivery and unclear ownership. How would you decide whether to extract a service?

    Listen for: A strong answer resists automatic decomposition. They should analyze domain boundaries, deployment pain, data ownership, coupling, team ownership, operational maturity, and transaction requirements. Good candidates consider modularizing inside the monolith first, using strangler patterns, published interfaces, and measuring whether extraction reduces or increases coordination cost.

    Red flag: They recommend microservices mainly because the codebase is large.

  4. 17How do you handle schema changes when multiple Java service versions may run during deployment?

    Listen for: They should describe backward-compatible migrations: expand and contract, nullable columns or defaults, dual reads/writes when needed, data backfills, feature flags, and ordered deploys. Good answers mention Flyway or Liquibase, testing migrations on realistic data, rollback constraints, and coordinating JPA mappings with database state.

    Red flag: They deploy code and destructive schema changes together and rely on quick rollback.

  5. 18A service processes messages from Kafka and occasionally produces duplicates downstream. How would you reason about the fix?

    Listen for: They should discuss at-least-once delivery, offset commits, consumer retries, poison messages, producer idempotence, transaction support, and downstream idempotency. Good answers identify where duplicates are created, add message keys or operation IDs, persist processing state when needed, and use dead-letter handling with alerting and replay procedures.

    Red flag: They assume Kafka exactly-once settings alone will remove all duplicate business effects.

  6. 19How would you set technical standards for error handling across several Java services?

    Listen for: Look for consistency without overengineering: domain exceptions, boundary translation, RFC 7807 problem details where appropriate, stable error codes, correlation IDs, structured logging, and retry classification. They should distinguish client errors, transient dependency failures, and programmer errors, and define how libraries should avoid leaking framework-specific exceptions.

    Red flag: They propose one global exception type for every failure.

  7. 20Describe how you would mentor a mid-level Java engineer who writes working code but struggles with design.

    Listen for: Strong answers include reviewing designs before implementation, pairing on refactoring, teaching domain modeling and dependency boundaries, using concrete examples from the codebase, and giving feedback on trade-offs rather than style preferences. They should set expectations, let the engineer own decisions, and follow up through code review and retrospectives.

    Red flag: They only suggest stricter code review comments or assigning simpler tasks.

System design Java questions

Designing real systems end to end.

  1. 21Design a Java service that receives order requests, reserves inventory, charges payment, and sends confirmation emails. How do you handle partial failures?

    Listen for: Strong answers identify that distributed transactions are usually inappropriate. They should use clear service boundaries, durable state transitions, sagas or orchestration, outbox events, idempotency keys, retries with backoff, compensating actions, and observable workflow status. Listen for how Java/Spring transactions interact with message publishing and external calls.

    Red flag: They wrap all steps in one @Transactional method and call external systems inside it.

  2. 22Design a multi-tenant Spring Boot API where each tenant’s data must be isolated and audited.

    Listen for: They should compare shared-schema, schema-per-tenant, and database-per-tenant approaches; explain tenant resolution, authorization, query filtering, migrations, backups, and operational overhead. Strong answers include audit tables or event logs, avoiding tenant IDs from untrusted input, test coverage for isolation, and safeguards against accidental cross-tenant access.

    Red flag: They add a tenant_id column but do not address authorization, migrations, or query enforcement.

  3. 23Design a Java-based report generation system for large datasets that users can download later.

    Listen for: Good answers avoid synchronous request processing. They should propose job submission, durable queues, worker services, chunked database reads, streaming file generation, object storage, progress state, cancellation, retry behavior, and resource limits. Listen for memory management, backpressure, GC impact, and using virtual threads only where appropriate.

    Red flag: They load all rows into memory and generate the file during the HTTP request.

  4. 24Design an authentication and authorization approach for a suite of Java microservices.

    Listen for: They should distinguish authentication at the edge from service authorization. Strong answers mention OAuth 2.1/OIDC, JWT validation, key rotation, scopes or permissions, service-to-service identity, propagation of user context, policy enforcement points, audit logging, and avoiding each service inventing its own security model.

    Red flag: They trust headers from upstream services without verification or clear network controls.

  5. 25Design observability for a Spring Boot platform running on Kubernetes.

    Listen for: A strong design includes structured logs, metrics, distributed traces, correlation IDs, health/readiness probes, dashboards tied to user-facing behavior, and alerting on symptoms rather than only resource usage. They should mention Micrometer, OpenTelemetry, Actuator, log sampling, PII handling, and how to debug JVM issues with JFR or thread dumps.

    Red flag: They only add more log statements and rely on checking pod logs manually.

Practical task · 2–3 hours

Build and Test a Small Order Processing API

Implement a Java 21 or 25 Spring Boot 3 service with endpoints to create an order and fetch order status. Creating an order should validate input, persist the order, call a provided fake inventory client, and record whether the order is ACCEPTED, REJECTED, or PENDING_RETRY when inventory is unavailable. Use PostgreSQL through Testcontainers or an equivalent local setup. Include meaningful automated tests for success, validation failures, duplicate client request IDs, and inventory failures. Keep the design small, but show clear boundaries between controller, service/domain logic, persistence, and external client code.

How to evaluate it

  • Clear domain modeling and separation of responsibilities
  • Correct handling of validation, idempotency, and failure states
  • Useful tests that run reliably without external services
  • Practical use of Spring Boot, JPA/JDBC, transactions, and configuration
  • Readable code, simple API design, and clear setup instructions

Rather skip the interview loop?

Every Octogle Java engineer has already passed a technical assessment, system design and a live interview with an engineer who has shipped Java. Send a brief and get 3–5 scored profiles in 48 hours.