Software & Engineering
Java Developer mock interview
A Java developer interview checks whether you understand what runs under your code: how a HashMap behaves when keys collide, what the memory model guarantees between threads, what the garbage collector is doing during a pause, and what Spring and Hibernate do behind your annotations. Expect core Java on the screen, concurrency and framework questions plus a coding task in the technical round, and a production story near the end.
The practice link on this page opens a technical round with the role set to Java Developer. The AI interviewer asks one question at a time and follows up when an answer stays at the level of a definition, for example by asking what you would see in a thread dump. A short round includes one coding exercise in the middle, set in a business problem rather than a textbook puzzle. Each answer is scored from 0 to 100 for relevance, depth and clarity, and the round report weighs code quality (25%), problem solving (30%), technical knowledge (25%) and communication (20%). Code quality only counts on the question where you wrote code.
Practice this role with an AI interviewer
Free plan: 2 interviews a month, free account, no card.
What the loop usually looks like
- Recruiter or technical screen (30 to 45 min). Core Java: collections, the equals and hashCode contract, checked versus unchecked exceptions, streams and Optional, and which Java version your current service runs. Expect one project you have to explain end to end.
- Technical round (45 to 60 min). Concurrency (executors, CompletableFuture, a race condition you fixed), Spring and JPA behaviour, and a coding exercise in a shared editor. Interviewers ask you to talk while you code and to say how you would test it.
- Design and behavioural (45 to 60 min). A service design such as an order or payment flow, then a production incident: an OutOfMemoryError, a thread pool that ran dry, a slow query that only showed up under load. Senior loops add a migration or a decision you would reverse.
What interviewers score
- How the runtime behaves under your code: heap, garbage collection, the memory model
- Concurrency that is correct, and sized for the work
- What Spring and JPA actually do with your annotations and entities
- Debugging in production with evidence: logs, thread dumps, GC logs, query counts
What interviewers probe at each level
Junior or fresher
The questions stay close to the language. What happens when two keys have the same hashCode? Why must equals and hashCode agree? When would you throw a checked exception? What does a stream pipeline do lazily? The follow-up is usually a small change to your answer, such as "and if the key object is mutable?", to see whether you reason or recite. College projects count, as long as you can explain the part you wrote.
Mid level
Expect code you have shipped. How did you size the executor, and what happened when the queue filled up? Why did a method marked @Transactional not roll back? How did you spot an N+1 query, and what did you change? Have you read a GC log? Interviewers want one real example per answer, with the symptom you saw and the number that told you it was fixed.
Senior and lead
Senior rounds want judgement. When would you move a service to virtual threads, and what would you check first? How do you set heap size and a pause goal for a latency-sensitive service? How did you run a Java 8 or 11 to 17 or 21 upgrade across a team? Expect a production incident told from detection to the change that stopped it recurring, and a design round scored on trade-offs.
Mistakes that cost candidates this round
- Explaining HashMap internals from memory of an old blog post, then getting stuck when asked what the Javadoc actually guarantees.
- Saying "use ConcurrentHashMap" without saying which operation was unsafe, or that a compound check-then-act still needs care.
- Answering every concurrency question with synchronized, and never mentioning executors, queues or what happens when the pool is full.
- Adding @Transactional to a private helper or calling it from the same class, and not knowing why nothing rolled back.
- Telling a GC tuning story that changed five flags at once and has no before and after numbers.
- Listing Java 17 and 21 features you have read about but never used, and freezing on the follow-up.
- Writing the coding exercise in silence, then explaining it at the end when there is no time left to fix it.
How do interviewers test Java concurrency and the memory model?
Most concurrency questions come back to one idea from chapter 17 of the Java Language Specification: two accesses to the same variable, at least one a write, that are not ordered by happens-before are a data race. A write to a volatile field happens-before every later read of that field, and a lock release happens-before the next acquire of the same lock. If you can say which of those edges protects a field in your own code, you can answer most of the follow-ups. If you can only say "volatile makes it visible", the interviewer will ask whether volatile makes count++ safe. It does not, because the increment is a read and a write.
HashMap questions start with collisions and end with threads. The Javadoc says the default load factor is 0.75, that the table is rehashed to about twice the buckets once the entry count passes capacity times load factor, and that when many keys share a hashCode and are Comparable the map may use their ordering to break ties. It also says the class is not synchronized and that its fail-fast iterators throw ConcurrentModificationException on a best-effort basis, to detect bugs only. Quote that last point when asked whether you can rely on the exception. ConcurrentHashMap is its own implementation, so explain which operations you needed to be atomic, such as computeIfAbsent, rather than saying it wraps a Hashtable.
For CompletableFuture, know two details that catch people out. Async methods with no Executor argument run on ForkJoinPool.commonPool(), so blocking I/O inside thenApplyAsync can starve every other user of that pool in the JVM. And join() throws an unchecked CompletionException while get() throws a checked ExecutionException with the same cause, which matters when you write the error handling.
Virtual threads now come up at mid and senior level. Oracle’s Java 21 guide says each virtual thread should represent one task and should never be pooled, so use Executors.newVirtualThreadPerTaskExecutor(). If you need to cap how many calls hit a slow service, use a Semaphore instead of a fixed pool. A virtual thread is pinned to its carrier while it runs inside a synchronized block. That only hurts when the block is long and frequent, for example I/O under a lock, and the fix the guide gives is a ReentrantLock. The JFR event jdk.VirtualThreadPinned records pinning that lasts longer than its threshold, which is 20 ms by default. All of this describes Java 21, so name the release your service runs before you answer a pinning question.
Sources: Java Language Specification SE 17, chapter 17: Threads and Locks; Oracle, Java SE 17 API: HashMap; Oracle, Java SE 17 API: CompletableFuture; Oracle, Java 21 core libraries: Virtual threads
Spring and JPA: where good candidates still go wrong
The classic Spring question is "why didn’t my transaction roll back?". The Spring reference gives two common answers. In proxy mode, which is the default, only calls that come in through the proxy are intercepted, so a method in the same class calling its own @Transactional method gets no transaction at all. And by default a RuntimeException or an Error triggers a rollback while a checked exception does not. Spring 6.2 adds a global switch, rollbackOn = ALL_EXCEPTIONS on @EnableTransactionManagement, and the reference recommends it. If your service is older than 6.2, the per-method answer is rollbackFor.
JPA questions centre on the N+1 problem. A list endpoint loads 50 orders, then lazily loads each order’s customer, and the log shows 51 queries. A good answer says how you found it (SQL logging or a query count in a test), then names the fix you chose: a join fetch in the query, an entity graph, or batch fetching. Spring Data JPA supports @EntityGraph on a repository method to set the fetch plan for that query. Say why you did not switch the association to eager everywhere, because that moves the cost to every other screen that loads the entity.
Interviewers also ask about bean scopes, constructor injection and what happens at startup, but the transaction and fetching questions are where mid-level candidates separate. Bring one story where an annotation did not do what you expected and what you read to find out why.
Sources: Spring Framework reference: Using @Transactional; Spring Data JPA reference: Query methods (fetch and load graphs)
What should a GC tuning story contain?
Senior candidates are often asked to describe a time they tuned garbage collection or fixed a memory problem. The strong answers follow one shape: the symptom (p99 latency spikes, a container killed for memory), the evidence (GC logs, a heap dump, allocation profiling), one change at a time, and a number before and after.
Know the defaults you are tuning from. Oracle’s G1 guide says G1 is the default collector and that MaxGCPauseMillis defaults to 200 ms, which is a goal G1 meets with high probability, not a guarantee. It also warns that fixing the young generation size with -XX:NewSize and -XX:MaxNewSize disables G1’s pause-time control. Many tuning stories that end in "we set the young gen size and pauses got worse" are explained by that one line.
Most memory incidents are not collector problems. A cache with no bound, a static map that only grows, or a large result set read into memory will fill any heap. Say how you told the difference between a leak and a heap that was simply too small for the load.
Sources: Oracle, Java 17 GC tuning guide: Garbage-First (G1) collector
How do I rehearse a Java interview here?
Start with the technical round from this page. Answer out loud, because the spoken explanation is what gets scored, and delivery feedback is speech-based: speaking pace, filler words (in English answers) and pauses, measured from your spoken answer. The coding exercise sits in the middle of the round. Its language comes from the job, so attach or paste a job post that asks for Java in the practice chat, or switch the Language menu above the editor to Java when the exercise opens. The interviewer reads your code and your explanation. Nothing runs it, so say what you would test and with which inputs.
Run a system design round as a second session for the order or payment service question. That round is scored on requirements analysis (20%), architecture design (30%), scalability & trade-offs (30%) and communication (20%). After each report, redo the single answer that scored lowest on depth, usually a concurrency or incident answer that stopped at the fix.
10 java developer interview questions and model answers
1. What happens inside a HashMap when two keys have the same hashCode, and when the map grows?
Technical. What they are testing: Whether you know the contract and the documented behaviour, not a half-remembered diagram.
Both keys land in the same bucket, so lookups fall back to equals to find the right entry. That is why equals and hashCode have to agree, and why a mutable key that changes after insertion can get lost. When the entry count passes capacity times the load factor, 0.75 by default, the table is rebuilt with about twice the buckets, which is why I presize a map when I know it will hold a large, known number of entries. If many keys share a hash and they are Comparable, the Javadoc says the map may use their ordering to break ties, so a pathological hash degrades less badly. None of this is thread-safe. HashMap is not synchronized.
2. You need to call three downstream services for one request and combine the results. How would you do it?
Technical. What they are testing: CompletableFuture composition, executors and failure handling.
I would start the three calls with supplyAsync on an executor I own, not the common pool, because these are blocking HTTP calls and the common pool is shared by the whole JVM. Then allOf to wait, and thenApply to combine. Each call gets a timeout with orTimeout, and I decide per call whether a failure fails the request or falls back to a default with exceptionally. On Java 21 I would look at virtual threads instead: one per call with newVirtualThreadPerTaskExecutor, plain blocking code, and a Semaphore if the downstream can only take so many requests.
3. Tell me about a race condition you found and fixed.
Technical. What they are testing: Real concurrency experience, and whether you can name the unsafe operation.
We had a counter of in-flight jobs in a plain int field that two scheduler threads updated. Under load the number drifted, and jobs stopped being picked up because the service thought it was at capacity. A thread dump showed nothing blocked, so I added logging around the increments and saw lost updates. count++ is a read and then a write, so two threads could both read 9 and write 10. I replaced it with an AtomicInteger and moved the check-and-increment into one compareAndSet loop. Then I wrote a test that hammered it from 32 threads and asserted the final count, and that test still runs in CI.
4. A method annotated @Transactional threw an exception, but the data was still committed. Why?
Technical. What they are testing: Spring proxy behaviour and default rollback rules.
Two things to check first. Was the method called from inside the same class? In the default proxy mode only calls through the proxy are intercepted, so a self-call runs with no transaction and each repository save commits on its own. Second, was it a checked exception? By default Spring rolls back on RuntimeException and Error, not on checked exceptions. In our case it was the second one, an IOException from a file upload. I added rollbackFor on that method, and on Spring 6.2 I would set rollbackOn to ALL_EXCEPTIONS for the whole application, which the reference recommends.
5. Your order list endpoint got slow as data grew. The logs show hundreds of queries per request. What is happening and how do you fix it?
Technical. What they are testing: Recognising N+1 and choosing a fix with its trade-off.
That is an N+1: one query for the orders, then one lazy load per order for the customer or the line items. I would confirm it with a query count, either Hibernate statistics or a test that asserts the number of statements. For this endpoint I would add an entity graph or a join fetch on the repository method, so customers come back in the same query. For a collection like line items with pagination I would use batch fetching instead, because a join fetch on a collection and paging do not mix well. I would not make the mapping eager everywhere, since every other screen would then pay for it.
6. How would you approach GC pauses that are pushing p99 latency over the target?
Technical. What they are testing: A measured tuning process, and knowledge of G1’s defaults.
First I would turn on GC logging and line up the pauses with the latency spikes, to make sure GC is actually the cause. On G1, the default, the pause goal is 200 ms unless someone changed it, and it is a goal, not a promise. Then I would look at allocation rate and live set size. If the live set keeps growing, it is a leak and no flag will fix it. If the heap is simply too small for the load, I would raise it and retest. I would change one thing at a time and keep the before and after p99. I would not pin the young generation size, because the G1 guide says that turns off pause-time control.
7. Which Java 17 or 21 features have you actually used, and where?
Technical. What they are testing: Current Java in real code, and honesty about what you have not used.
Records for DTOs and event payloads, which removed a lot of Lombok. Sealed interfaces for a payment result type, so a switch over the subtypes is exhaustive and the compiler tells us when someone adds a case. Pattern matching for switch arrived as a final feature in Java 21, and we started using it after the upgrade. I have tried virtual threads in a load test of one I/O-heavy service and they held up well, but we have not shipped them, because two libraries we depend on did I/O inside synchronized blocks and I wanted to check pinning with JFR first.
8. Tell me about a production incident in a Java service you owned.
Behavioral. What they are testing: Calm sequencing, evidence and a fix that stops it recurring.
Our pricing service started returning timeouts at 9 a.m. on a Monday. Heap was fine, CPU was low, but the request pool was exhausted. A thread dump showed every request thread waiting on a connection from the database pool, and the pool was held by a nightly report job that had been moved to daytime. I stopped the job, which cleared it within a minute. The lasting fix was a separate connection pool for batch work and an alert on pool wait time. I also added the thread dump to our runbook, because it took us twenty minutes to think of taking one.
9. You are asked to upgrade a large Spring service from Java 11 to 21. How would you plan it?
Situational. What they are testing: Risk management on a real migration.
I would check the framework versions first, because recent Spring releases need a newer baseline than Java 11, so the Java upgrade and the Spring upgrade may have to happen together. Then build on 21 in CI while still running 11 in production, fix compile errors and deprecated APIs, and run the full test suite and a load test. I would compare GC and latency numbers before and after, since collector defaults and ergonomics change between releases. Then release to one instance or a canary, watch it for a day, and roll out. Language features like records come after the upgrade is stable, not as part of it.
10. Write a method that returns the top three products by revenue from a list of orders. Talk me through it.
Domain. What they are testing: Clean Java in a business setting, plus testing instincts.
I would restate it first: revenue is quantity times unit price summed per product, and I need to decide what happens on a tie. Then a stream that flatMaps orders to line items, groups by product ID with a summing collector on a BigDecimal, sorts the entries by value descending and takes three. I would use BigDecimal, not double, because this is money. Then I would say the tests: an empty list, fewer than three products, a tie at third place, and a product that appears in many orders. If the list could be very large, I would mention a bounded priority queue instead of sorting everything.
Frequently asked questions
What Java topics come up most in a developer interview?
Collections and the equals and hashCode contract, exceptions, streams, concurrency (executors, CompletableFuture, thread safety), Spring and JPA behaviour, and from mid level up, a production incident and some JVM memory and GC knowledge. Senior loops add a design round and a migration or architecture decision.
Which Java version should I talk about in the interview?
The one your service actually runs, then what you know about newer LTS releases. Oracle’s release notes list records as final in Java 16, sealed classes in 17, and pattern matching for switch and record patterns in 21. Only claim features you have used, because the follow-up will ask where.
Will the coding exercise be in Java?
Only if something tells it to. The exercise language is taken from the job post first, then from your skills, and the role title alone does not set it, so a round with no Java job post and no Java skill opens in Python. Attach or paste a Java job post in the practice chat, or switch the editor’s Language menu to Java when the exercise opens. The interviewer reads your code and your explanation. Nothing executes it.
Can I practise a Java mock interview for free?
Yes. The free plan is 2 interviews a month, free account, no card. Each of those can be the Java technical round from this page, coding exercise and report included.
Keep practicing
- Backend Developer mock interview
- Full-Stack Developer mock interview
- Software Engineer mock interview
- Python Developer mock interview
- Technical interview practice with AI
- System design interview framework
- How to prepare for coding interviews
- Salesforce developer mock interview
- Free AI mock interview (2 interviews a month, free account, no card)
- AI mock interview tools compared
- Questions every round asks, with worked answers
- Practice in another language
- All role mock interviews