Java Developer Interview Questions
Prepare for your Java Developer interview. Understand the required skills and qualifications, anticipate the questions you may be asked, and study well-prepared answers using our sample responses.
Interview Questions for Java Developer
When would you choose a HashMap over a TreeMap, and what are the implications for performance and ordering?
Tell me about a time you diagnosed and fixed a concurrency bug in a Java service.
How would you use CompletableFuture to run multiple I/O calls in parallel, handle timeouts, and combine the results?
A service shows frequent Full GCs and latency spikes after a traffic increase. How do you investigate and tune the JVM?
What is your process for designing and implementing a robust REST API with Spring Boot?
How do you detect and prevent the N+1 query problem in JPA/Hibernate?
Can you explain transaction propagation and isolation in Spring, and when you would change the defaults?
In a startup where speed matters, how do you balance unit, integration, and end-to-end tests without slowing delivery?
If you were tasked with designing a URL shortener that handles 10k requests per second, how would you architect it in Java?
After a deploy, a key endpoint’s p95 latency tripled. Walk me through your debugging steps.
What’s your approach to API versioning and maintaining backward compatibility as clients evolve?
Describe your experience building event-driven systems with Kafka or similar. How do you ensure idempotency and ordering where needed?
How do you implement resilient external calls in Java, including timeouts, retries with backoff, and circuit breaking?
How would you secure a Spring Boot microservice using OAuth2 and JWTs?
What steps do you take to containerize a Java application and optimize its runtime footprint for the cloud?
What observability would you add to a new service from day one?
When moving fast in a small team, how do you maintain code quality without creating bottlenecks?
In a resource-constrained startup, how do you decide between shipping a new feature and tackling technical debt?
Tell me about a time you had to deliver with ambiguous requirements and shifting priorities.
How would you help shape a healthy engineering culture in an early-stage company?
Describe a time you worked closely with product or design to slice an MVP and iterate quickly.
How do you stay current with Java and ecosystem changes, and can you share a recent feature you adopted?
Tell me about a production incident you owned. What went wrong, and what did you change afterward?
Why are you interested in joining our startup, and how do you see yourself making an impact in the next 90 days?
-
When would you choose a HashMap over a TreeMap, and what are the implications for performance and ordering?
Employers ask this question to assess your core Java collections knowledge and your ability to select the right data structure. In your answer, compare time complexity, ordering needs, and typical use cases, and briefly note thread-safety considerations.
Answer Example: "I use HashMap for average O(1) lookups and inserts when I don’t need ordering, and TreeMap when I need keys sorted with O(log n) operations. For example, I used TreeMap for a time-ordered view, but switched to HashMap plus a separate list to cut latency under load. Neither is thread-safe, so I use ConcurrentHashMap or external synchronization in concurrent code."
Help us improve this answer. / -
Tell me about a time you diagnosed and fixed a concurrency bug in a Java service.
Employers ask this to understand your practical experience with multithreading issues like race conditions, deadlocks, and visibility problems. In your answer, describe the symptoms, how you reproduced it, the tools or techniques you used, and the specific fix and tests you added.
Answer Example: "We saw intermittent stale reads in a cache layer under high parallelism. I reproduced it with a stress test and JFR, identified non-atomic updates, and replaced a shared HashMap with ConcurrentHashMap and AtomicReference updates. I added thread-safety tests and a race detector via jcstress to prevent regressions."
Help us improve this answer. / -
How would you use CompletableFuture to run multiple I/O calls in parallel, handle timeouts, and combine the results?
Employers ask this to gauge your grasp of asynchronous patterns and resource efficiency. In your answer, outline composing futures, using allOf or anyOf, applying timeouts, and handling failures gracefully.
Answer Example: "I submit suppliers to a bounded Executor and compose them with CompletableFuture.allOf to run in parallel. I apply orTimeout or completeOnTimeout for each call, then combine results with thenCombine or by joining after allOf completes. Failures get mapped to partial results and logged, and I propagate a clear error if a critical dependency fails."
Help us improve this answer. / -
A service shows frequent Full GCs and latency spikes after a traffic increase. How do you investigate and tune the JVM?
Employers ask this to see your understanding of JVM memory management and performance tuning. In your answer, describe how you gather evidence, analyze allocation patterns, and iterate on changes safely.
Answer Example: "I start by enabling GC logs and capturing JFR to see allocation rates, pause times, and hotspots. I look for large object churn or leaks with heap dumps and tools like Eclipse MAT or YourKit. Based on findings, I adjust heap sizes, switch or tune the GC (G1 vs ZGC), reduce allocations in hot paths, and validate improvements with load tests before production."
Help us improve this answer. / -
What is your process for designing and implementing a robust REST API with Spring Boot?
Employers ask this to evaluate your architecture thinking and familiarity with Spring Boot best practices. In your answer, cover layering, validation, error handling, documentation, and testing.
Answer Example: "I start with clear resource modeling and versioning, then implement controllers, services, and repositories with DTOs and validation via Bean Validation. I add global exception handling with @ControllerAdvice, OpenAPI docs, and consistent error formats. I write unit and slice tests plus a few end-to-end tests with Testcontainers for the data layer."
Help us improve this answer. / -
How do you detect and prevent the N+1 query problem in JPA/Hibernate?
Employers ask this to check your ORM experience and ability to write efficient persistence code. In your answer, mention detection techniques, fetch strategies, and trade-offs.
Answer Example: "I detect N+1 by inspecting logs with SQL logging and Hibernate statistics, and by using integration tests with Testcontainers to measure query counts. To prevent it, I use fetch joins or entity graphs for read paths, and prefer pagination to limit result sets. I’m careful to avoid over-fetching and default to lazy loading unless a use case demands eager."
Help us improve this answer. / -
Can you explain transaction propagation and isolation in Spring, and when you would change the defaults?
Employers ask this to ensure you can reason about data consistency and side effects. In your answer, explain common propagation settings and isolation levels with practical scenarios.
Answer Example: "I use REQUIRED as a default so calls join the existing transaction, switching to REQUIRES_NEW for audit logging that must commit independently. For isolation, I default to the database default (often READ COMMITTED) but raise it to REPEATABLE READ for financial calculations to prevent non-repeatable reads. I also keep transactions short and avoid starting them in controllers."
Help us improve this answer. / -
In a startup where speed matters, how do you balance unit, integration, and end-to-end tests without slowing delivery?
Employers ask this to see how you manage risk and quality under time pressure. In your answer, talk about the test pyramid, automation, and pragmatic trade-offs.
Answer Example: "I follow a test pyramid: fast unit tests for logic, selective integration tests for persistence and messaging using Testcontainers, and a few critical end-to-end smoke tests. I gate merges on the first two and run e2e nightly and pre-release. When under tight deadlines, I still write characterization tests on risky code paths and add missing tests right after the release."
Help us improve this answer. / -
If you were tasked with designing a URL shortener that handles 10k requests per second, how would you architect it in Java?
Employers ask system design questions to assess your ability to translate requirements into scalable, reliable systems. In your answer, cover data modeling, APIs, concurrency, storage, and bottlenecks.
Answer Example: "I would build a stateless Spring Boot service behind a load balancer with a base62 ID generator using a segment allocator to avoid contention. Writes go to a primary database (e.g., PostgreSQL with a monotonic sequence or Redis for counters) and are asynchronously replicated to a cache like Redis. I’d add rate limiting, a read-through cache for lookups, and observability to monitor latency and errors."
Help us improve this answer. / -
After a deploy, a key endpoint’s p95 latency tripled. Walk me through your debugging steps.
Employers ask this to evaluate your operational maturity and structured problem-solving. In your answer, show how you isolate variables, use observability, and roll back or fix safely.
Answer Example: "I compare metrics and traces between versions to identify which spans slowed down and whether it’s code, dependency, or infrastructure. If the issue is severe, I roll back quickly, then analyze diffs, JVM metrics, GC behavior, and database query plans. I reproduce with a canary or load test and apply a targeted fix before a careful redeploy."
Help us improve this answer. / -
What’s your approach to API versioning and maintaining backward compatibility as clients evolve?
Employers ask this to ensure you can ship changes without breaking consumers. In your answer, discuss versioning strategy, deprecation, and communication.
Answer Example: "I prefer URI or header-based versioning, keeping responses backward compatible by adding fields and avoiding breaking changes. For removals, I mark fields deprecated, communicate timelines, and provide dual-write or adapter layers during migration. Contract tests in CI ensure we don’t accidentally break existing clients."
Help us improve this answer. / -
Describe your experience building event-driven systems with Kafka or similar. How do you ensure idempotency and ordering where needed?
Employers ask this to probe your understanding of messaging semantics and reliability. In your answer, mention delivery guarantees, keying strategy, and consumer design.
Answer Example: "I use at-least-once delivery and ensure idempotency with deterministic keys and upserts or dedup tables. For ordering, I partition by entity key so related events land in the same partition and process sequentially. Consumers handle retries with backoff and commit offsets only after successful processing."
Help us improve this answer. / -
How do you implement resilient external calls in Java, including timeouts, retries with backoff, and circuit breaking?
Employers ask this to see your ability to build reliable services that fail gracefully. In your answer, describe libraries or patterns and how you tune them.
Answer Example: "I set client timeouts explicitly, implement retries with exponential backoff and jitter, and use a circuit breaker via Resilience4j or similar. I differentiate between retryable and non-retryable errors, cap retries to avoid thundering herds, and propagate meaningful errors. Metrics and logs track retry rates and open circuits for visibility."
Help us improve this answer. / -
How would you secure a Spring Boot microservice using OAuth2 and JWTs?
Employers ask this to confirm you can implement practical service-level security. In your answer, cover authentication, authorization, and least-privilege access.
Answer Example: "I configure the service as a resource server with spring-security-oauth2, validating JWTs from a trusted issuer and enforcing scopes or roles on endpoints. I apply method-level authorization for sensitive operations and validate inputs to prevent injection. Secrets go in a secure store, and I rotate keys while monitoring auth failures."
Help us improve this answer. / -
What steps do you take to containerize a Java application and optimize its runtime footprint for the cloud?
Employers ask this to evaluate your DevOps awareness and cost-consciousness. In your answer, discuss image sizing, memory settings, and startup time.
Answer Example: "I build a slim image with a multi-stage Dockerfile and a distroless or Alpine base, use a JRE not JDK, and layer dependencies efficiently. I set JVM flags for container awareness and tune heap based on limits, and I prefer G1 or ZGC for low latency. I also preheat application caches and use AppCDS or spring-aot if startup time is critical."
Help us improve this answer. / -
What observability would you add to a new service from day one?
Employers ask this to see if you build diagnosable systems. In your answer, include metrics, logs, and tracing with actionable detail.
Answer Example: "I expose key RED metrics (requests, errors, duration) with percentiles, domain-specific KPIs, and JVM metrics. I standardize structured logging with correlation IDs and add distributed tracing via OpenTelemetry to follow requests across services. Dashboards and SLO alerts help catch regressions early."
Help us improve this answer. / -
When moving fast in a small team, how do you maintain code quality without creating bottlenecks?
Employers ask this to assess your judgment about process and pragmatism. In your answer, mention automation, review focus, and conventions.
Answer Example: "I lean on automated checks (formatting, static analysis, and unit tests) to keep reviews focused on architecture and readability. I practice small PRs, pair on complex changes, and document decisions briefly in the repo. I also add lint rules and quality gates in CI to catch issues early."
Help us improve this answer. / -
In a resource-constrained startup, how do you decide between shipping a new feature and tackling technical debt?
Employers ask this to understand your prioritization and product sense. In your answer, tie technical decisions to business impact and risk.
Answer Example: "I quantify the cost of delay for the feature and the risk and drag caused by the debt, then propose the smallest slice that delivers value while addressing the highest-impact debt. For example, I shipped an MVP with a simple path and concurrently refactored a hotspot that was causing incidents. I present trade-offs with data so stakeholders can make informed choices."
Help us improve this answer. / -
Tell me about a time you had to deliver with ambiguous requirements and shifting priorities.
Employers ask this to evaluate your comfort with ambiguity and ability to create clarity. In your answer, show how you drive alignment and still execute.
Answer Example: "I set up a quick alignment session to define success criteria and constraints, then proposed a strawman design for feedback. I time-boxed discovery, built the thinnest vertical slice, and validated it with users before iterating. Regular check-ins kept stakeholders aligned as priorities shifted."
Help us improve this answer. / -
How would you help shape a healthy engineering culture in an early-stage company?
Employers ask this to gauge your leadership mindset beyond code. In your answer, focus on habits that scale, documentation lightweights, and inclusivity.
Answer Example: "I model writing crisp RFCs and decision records, keep processes lightweight, and encourage blameless postmortems. I push for pair programming on gnarly areas, rotate on-call, and celebrate shipping as well as learning from failures. I also mentor juniors and create space for tech debt sprints."
Help us improve this answer. / -
Describe a time you worked closely with product or design to slice an MVP and iterate quickly.
Employers ask this to see cross-functional collaboration and product thinking. In your answer, show how you balance scope, quality, and learning.
Answer Example: "I partnered with product and design to define must-have user flows and deferred non-critical polish. We shipped a functional MVP behind a feature flag, captured usage metrics, and iterated on top pain points. This cut time-to-value in half while keeping the codebase maintainable."
Help us improve this answer. / -
How do you stay current with Java and ecosystem changes, and can you share a recent feature you adopted?
Employers ask this to confirm continuous learning and practical application. In your answer, mention sources and a concrete example of impact.
Answer Example: "I follow OpenJDK updates, read community blogs, and experiment in small spikes. Recently I adopted virtual threads in Java 21 for a high-concurrency batch importer, simplifying code and improving throughput without complex thread pools. We measured a 30% reduction in latency at peak load."
Help us improve this answer. / -
Tell me about a production incident you owned. What went wrong, and what did you change afterward?
Employers ask this to assess accountability and learning from mistakes. In your answer, be candid, focus on root cause and systemic fixes, not blame.
Answer Example: "A misconfigured database connection pool caused thread starvation during a traffic spike. I led the rollback, added safeguards with timeouts and bulkheads, and tuned the pool based on load testing. We also added a runbook and alerts on queue depth and thread pool saturation."
Help us improve this answer. / -
Why are you interested in joining our startup, and how do you see yourself making an impact in the next 90 days?
Employers ask this to gauge motivation, alignment with the mission, and your bias for action. In your answer, connect your skills to their product and stage, and propose a concrete ramp-up plan.
Answer Example: "I’m excited by your mission in [domain] and the chance to build core systems early when decisions matter most. In the first 90 days, I’d ship value by owning a service end to end, harden CI/CD and observability, and reduce a top performance bottleneck. I thrive in small teams where I can code, collaborate with product, and improve engineering practices."
Help us improve this answer. /