Skip to content
Resume Studioby M2Toolkit

10 role-specific questions

Java Developer Interview Questions & Answers

Java interviews cover the language and collections, the JVM and memory, concurrency, and building services with Spring Boot.

Free, no sign-up. 83 questions in this role's practice pool, including behavioural, HR and situational questions.

Java & Spring interview questions

Core Java, collections, the JVM, concurrency and Spring Boot.

  1. 1.

    Why must you override hashCode when you override equals in Java?

    BeginnerTechnical

    What the interviewer is evaluating

    Understanding of the collections contract.

    Key points a strong answer covers

    • The contract. Equal objects must have equal hash codes.
    • Hash-based collections. HashMap and HashSet use hashCode to find the bucket, then equals.
    • What breaks. Without it, equal objects land in different buckets — lookups fail and duplicates appear.
    • Mutable keys / records. Use immutable fields for keys; records generate both correctly.

    Suggested answer structure

    1. Define it in one sentence.
    2. Explain how it works underneath.
    3. Give a practical example from code or a project.
    4. Close with a trade-off, pitfall or when you'd use it.

    Common mistakes

    • Thinking equal hash codes mean equal objects.
    • Using mutable fields in hashCode for map keys.

    Likely follow-up questions

    • What happens if a key's fields change after it's put in a HashMap?
    • Do equal hash codes imply equal objects?
    Example strong answer

    The contract says that if two objects are equal according to equals, they must return the same hashCode. Hash-based collections rely on it: HashMap and HashSet use the hash code to pick a bucket and only then call equals within that bucket. If I override equals so two Email objects with the same address are equal but leave the default identity hashCode, they land in different buckets — set.contains(new Email("a@b.com")) returns false and duplicates creep in. The reverse isn't required: different objects may share a hash code. I base both on the same immutable fields — Objects.hash(...) — or use a record, which generates both correctly.

    Practise this question and get feedback
  2. 2.

    Compare ArrayList, LinkedList, HashMap and TreeMap.

    BeginnerTechnical

    What the interviewer is evaluating

    Choosing collections by performance characteristics.

    Key points a strong answer covers

    • ArrayList. ArrayList: backed by an array, O(1) index access, amortised O(1) append.
    • LinkedList. LinkedList: linked nodes, O(n) access; rarely faster in practice.
    • HashMap. HashMap: O(1) average lookups, no order.
    • TreeMap. TreeMap: sorted keys, O(log n) operations.
    • Others. LinkedHashMap keeps insertion order; ConcurrentHashMap for concurrency.

    Suggested answer structure

    1. Define it in one sentence.
    2. Explain how it works underneath.
    3. Give a practical example from code or a project.
    4. Close with a trade-off, pitfall or when you'd use it.

    Common mistakes

    • Choosing LinkedList for fast inserts without measuring.
    • Using HashMap where iteration order matters.

    Likely follow-up questions

    • When would LinkedHashMap be the right choice?
    • Why is ArrayDeque usually better than LinkedList as a queue?
    Example strong answer

    ArrayList is backed by an array: O(1) access by index and amortised O(1) appends, and it's cache-friendly — my default list. LinkedList is a chain of nodes: O(n) to reach an index, and despite its reputation for cheap inserts it's rarely faster in practice; for queues ArrayDeque is better. HashMap gives O(1) average lookups with no ordering guarantee; LinkedHashMap keeps insertion order — handy for an LRU cache. TreeMap keeps keys sorted using a red-black tree, with O(log n) operations and range queries like headMap. For concurrent access I use ConcurrentHashMap rather than synchronising a HashMap.

    Practise this question and get feedback
  3. 3.

    Describe JVM memory: the heap, the stack and garbage collection.

    IntermediateTechnical

    What the interviewer is evaluating

    Runtime knowledge for troubleshooting.

    Key points a strong answer covers

    • Stack per thread. Each thread has a stack of frames holding local variables and references.
    • Heap shared. Objects live on the shared heap.
    • Generational GC. GC is generational: young (eden/survivor) and old generations.
    • Collectors / tuning. Collectors like G1 and ZGC trade throughput and pause times; -Xmx sizes the heap.
    • Errors. OutOfMemoryError vs StackOverflowError; heap dumps to investigate.

    Suggested answer structure

    1. Define it in one sentence.
    2. Explain how it works underneath.
    3. Give a practical example from code or a project.
    4. Close with a trade-off, pitfall or when you'd use it.

    Common mistakes

    • Saying Java has no memory leaks because of GC.
    • Mixing up StackOverflowError and OutOfMemoryError.

    Likely follow-up questions

    • How would you investigate an OutOfMemoryError in production?
    • What's metaspace?
    Example strong answer

    Each thread has its own stack of frames holding method parameters, local primitives and references; deep recursion overflows it with a StackOverflowError. Objects live on the shared heap, which the garbage collector manages. Most JVM collectors are generational: new objects go to the young generation's eden space, survivors move through survivor spaces, and long-lived objects are promoted to the old generation, which is collected less often. G1 is the default and balances throughput and pauses; ZGC targets very low pause times for big heaps. Leaks still happen — static collections that grow, unclosed resources — so for an OutOfMemoryError I capture a heap dump and analyse it with Eclipse MAT or VisualVM.

    Practise this question and get feedback
  4. 4.

    How do you write thread-safe code in Java?

    AdvancedTechnical

    What the interviewer is evaluating

    Concurrency correctness.

    Key points a strong answer covers

    • Shared mutable state. Problems come from shared mutable state and race conditions.
    • Immutability. Prefer immutable objects.
    • Synchronisation. Use synchronized, locks, volatile for visibility and atomics.
    • Concurrent utilities. Use java.util.concurrent: executors, ConcurrentHashMap, CompletableFuture.
    • Virtual threads. Java 21 virtual threads make blocking I/O code scale cheaply.

    Suggested answer structure

    1. Define it in one sentence.
    2. Explain how it works underneath.
    3. Give a practical example from code or a project.
    4. Close with a trade-off, pitfall or when you'd use it.

    Common mistakes

    • Thinking volatile makes compound operations like count++ atomic.
    • Creating raw threads instead of using executors.

    Likely follow-up questions

    • Why isn't count++ thread-safe even on a volatile field?
    • What problem do virtual threads solve?
    Example strong answer

    Most concurrency bugs come from shared mutable state, so my first move is to avoid it: immutable objects, records, and confining state to one thread. When state must be shared, I use the right tool: synchronized or a ReentrantLock for compound operations, volatile only for visibility of a simple flag — it doesn't make count++ atomic — and AtomicInteger or LongAdder for counters. I lean on java.util.concurrent: ConcurrentHashMap, executors instead of raw threads, CompletableFuture for composing async work. With Java 21, virtual threads let you write simple blocking code for I/O-heavy servers that scales to many thousands of concurrent tasks.

    Practise this question and get feedback
  5. 5.

    How does dependency injection work in Spring Boot?

    IntermediateTechnical

    What the interviewer is evaluating

    Core Spring understanding.

    Key points a strong answer covers

    • IoC container / beans. Spring's IoC container creates and wires beans.
    • Component scanning. Classes annotated @Component/@Service are discovered; @Bean methods define others.
    • Constructor injection. Prefer constructor injection with final fields.
    • Scopes. Beans are singletons by default.
    • Testability / auto-config. Easy to test with mocks; auto-configuration wires common beans.

    Suggested answer structure

    1. Define it in one sentence.
    2. Explain how it works underneath.
    3. Give a practical example from code or a project.
    4. Close with a trade-off, pitfall or when you'd use it.

    Common mistakes

    • Field injection everywhere.
    • Assuming beans are created per request by default.

    Likely follow-up questions

    • Why is constructor injection preferred over field injection?
    • How does Spring Boot auto-configuration decide what to create?
    Example strong answer

    Spring's IoC container creates objects called beans and wires their dependencies. Classes annotated with @Component, @Service, @Repository or @RestController are found by component scanning, and @Bean methods in @Configuration classes define others, like third-party clients. I use constructor injection with final fields — with a single constructor no @Autowired is needed — which makes dependencies explicit, supports immutability, and lets tests construct the class with mocks. Beans are singletons by default, so they must be stateless or thread-safe. Spring Boot's auto-configuration adds sensible beans based on what's on the classpath and your properties, which you can override with your own.

    Practise this question and get feedback
  6. 6.

    How does @Transactional work in Spring, and what are its pitfalls?

    AdvancedTechnical

    What the interviewer is evaluating

    Avoiding subtle data bugs in Spring applications.

    Key points a strong answer covers

    • Proxy-based. @Transactional works through a proxy around the bean.
    • Self-invocation pitfall. Calling a transactional method from the same class bypasses the proxy.
    • Rollback rules. By default only unchecked exceptions trigger rollback.
    • Propagation. Propagation controls joining or starting transactions.
    • Public / boundaries. Put it on public service methods; keep transactions short — no slow external calls inside.

    Suggested answer structure

    1. Define it in one sentence.
    2. Explain how it works underneath.
    3. Give a practical example from code or a project.
    4. Close with a trade-off, pitfall or when you'd use it.

    Common mistakes

    • Expecting @Transactional on a private method or self-call to work.
    • Calling an external HTTP API inside a database transaction.

    Likely follow-up questions

    • Why doesn't a checked exception roll back by default?
    • When would you use REQUIRES_NEW?
    Example strong answer

    @Transactional is implemented with a proxy: Spring wraps the bean, and when a caller invokes the annotated method through the proxy, it opens a transaction, runs the method and commits — or rolls back if an exception escapes. That proxy model causes the main pitfalls. Calling a transactional method from another method in the same class bypasses the proxy, so no transaction starts. By default only unchecked exceptions trigger a rollback; checked ones commit unless you set rollbackFor. Propagation decides whether a method joins the existing transaction or starts a new one with REQUIRES_NEW, for example for an audit log that must persist even if the main work fails. I keep transactions on service methods and short, never wrapping slow external calls.

    Practise this question and get feedback
  7. 7.

    Explain Java Streams. When would you use them, and when not?

    IntermediateTechnical

    What the interviewer is evaluating

    Idiomatic modern Java.

    Key points a strong answer covers

    • Declarative pipeline. Streams express a pipeline of operations like filter, map and collect.
    • Lazy / terminal. Intermediate operations are lazy until a terminal operation runs.
    • Single use. A stream can only be consumed once.
    • Parallel caution. parallelStream only helps for large CPU-bound work — measure.
    • When not. Simple loops can be clearer; avoid side effects inside streams.

    Suggested answer structure

    1. Define it in one sentence.
    2. Explain how it works underneath.
    3. Give a practical example from code or a project.
    4. Close with a trade-off, pitfall or when you'd use it.

    Common mistakes

    • Using parallelStream by default.
    • Mutating external state inside forEach.

    Likely follow-up questions

    • What's the difference between map and flatMap?
    • How would you group a list of orders by status?
    Example strong answer

    Streams let you describe a data pipeline declaratively: orders.stream().filter(o -> o.total() > 100).map(Order::customerId).distinct().toList(). Intermediate operations like filter and map are lazy; nothing runs until a terminal operation such as collect, toList or count, and a stream can only be consumed once. Collectors make grouping easy — Collectors.groupingBy(Order::status). I avoid side effects inside streams, and I don't reach for parallelStream by default: it uses the common fork-join pool and only helps for large CPU-bound work, which I'd measure. When logic needs early exits, checked exceptions or complex state, a plain loop is often clearer.

    Practise this question and get feedback
  8. 8.

    What's the difference between checked and unchecked exceptions in Java?

    BeginnerTechnical

    What the interviewer is evaluating

    Error-handling design.

    Key points a strong answer covers

    • Checked must be declared/handled. Checked exceptions must be caught or declared with throws — the compiler enforces it.
    • Unchecked = RuntimeException. Unchecked exceptions extend RuntimeException and aren't enforced.
    • When to use. Checked for recoverable conditions; unchecked for programming errors.
    • Good practice. Don't swallow exceptions; wrap with cause; use try-with-resources.

    Suggested answer structure

    1. Define it in one sentence.
    2. Explain how it works underneath.
    3. Give a practical example from code or a project.
    4. Close with a trade-off, pitfall or when you'd use it.

    Common mistakes

    • Empty catch blocks.
    • Catching Exception broadly everywhere.

    Likely follow-up questions

    • Why do many modern frameworks prefer unchecked exceptions?
    • What does try-with-resources do?
    Example strong answer

    Checked exceptions — subclasses of Exception but not RuntimeException, like IOException — must be caught or declared with throws; the compiler enforces it. Unchecked exceptions extend RuntimeException — NullPointerException, IllegalArgumentException — and aren't enforced. The traditional guidance is checked for conditions a caller can reasonably recover from, unchecked for programming errors. In practice many frameworks, including Spring, prefer unchecked exceptions because checked ones leak through layers and get wrapped or swallowed. Whatever the type, I never leave an empty catch, I wrap with the original as the cause so the stack trace survives, and I use try-with-resources so streams and connections are always closed.

    Practise this question and get feedback
  9. 9.

    How would you build and structure a REST API with Spring Boot?

    IntermediateTechnical

    What the interviewer is evaluating

    Practical Spring web development.

    Key points a strong answer covers

    • Controllers. @RestController with mapping annotations.
    • Layers. Controller → service → repository, with DTOs separate from entities.
    • Validation. Bean Validation with @Valid on request DTOs.
    • Error handling. @RestControllerAdvice for consistent errors (ProblemDetail).
    • Data & docs. Spring Data JPA repositories, Pageable, OpenAPI docs.

    Suggested answer structure

    1. Define it in one sentence.
    2. Explain how it works underneath.
    3. Give a practical example from code or a project.
    4. Close with a trade-off, pitfall or when you'd use it.

    Common mistakes

    • Returning JPA entities directly from controllers.
    • Putting business logic in controllers.

    Likely follow-up questions

    • Why separate DTOs from entities?
    • How would you paginate a large result set?
    Example strong answer

    I'd structure it in layers. @RestController classes handle HTTP — mapping with @GetMapping/@PostMapping, binding request DTOs with @Valid so Bean Validation rejects bad input — and delegate to @Service classes that hold business logic and transactions. Spring Data JPA repositories handle persistence, and I accept a Pageable for list endpoints. DTOs are separate from JPA entities, so the API contract doesn't change when the schema does and we don't accidentally expose fields or trigger lazy loading during serialisation. A @RestControllerAdvice maps exceptions to consistent ProblemDetail responses. springdoc generates OpenAPI documentation, and Actuator exposes health and metrics.

    Practise this question and get feedback
  10. 10.

    What is Optional in Java, and how should it be used?

    BeginnerTechnical

    What the interviewer is evaluating

    Null-safety idioms: using Optional where it helps and not where it hurts.

    Key points a strong answer covers

    • Represents maybe-absent value. Optional represents a value that may be absent, instead of returning null.
    • Return types. Intended mainly as a return type — e.g. findById.
    • Use the API. Use map, orElse, orElseThrow instead of get().
    • Don't overuse. Not for fields, parameters or collections; avoid calling get() unchecked.

    Suggested answer structure

    1. Define it in one sentence.
    2. Explain how it works underneath.
    3. Give a practical example from code or a project.
    4. Close with a trade-off, pitfall or when you'd use it.

    Common mistakes

    • Calling .get() without checking.
    • Using Optional as a field or method parameter.

    Likely follow-up questions

    • What's the difference between orElse and orElseGet?
    • Should a method return Optional<List<T>>?
    Example strong answer

    Optional<T> is a container that either holds a value or is empty, so a method like findById can make 'not found' explicit in its type instead of returning null. It's designed mainly for return types. Callers then use its API — map to transform, orElse or orElseGet for a default, orElseThrow to turn absence into an exception — rather than calling get() unchecked, which just recreates the NullPointerException. I don't use it for fields, parameters or collections; an empty list is better than Optional<List>. One subtlety: orElse always evaluates its argument, while orElseGet only calls the supplier when needed.

    Practise this question and get feedback

Behavioural & HR questions you'll also get

These come up in almost every java developer interview. Story questions are best answered with STAR — Situation, Task, Action, Result.

  • Tell me about yourself.

    BeginnerHR

    What the interviewer is evaluating

    Whether you can give a concise, relevant pitch that frames your experience around this job.

    Key points a strong answer covers

    • Present. Start with your current role and what you do.
    • Relevant past. Pick the most relevant past experience.
    • Strength / achievement. Include one strength or achievement with evidence.
    • Why this role. Finish with why this role is the next step.

    Suggested answer structure

    1. Present — your current role in one or two sentences.
    2. Past — the experience most relevant to this job.
    3. Proof — one achievement or strength with evidence.
    4. Future — why this role is the logical next step.

    Common mistakes

    • Reciting your whole CV chronologically.
    • Personal life story unrelated to the job.
    • Going over two minutes.

    Likely follow-up questions

    • Why are you looking to leave your current role?
    • What would your manager say is your biggest strength?
    Example strong answer

    I'm a front-end developer with four years' experience, currently at a fintech start-up where I build the customer dashboard in React and TypeScript. Before that I spent two years at an agency building e-commerce sites, which taught me to work fast with lots of different clients. The thing I'm proudest of recently is leading our move to a shared component library, which cut the time to build new screens by about a third. I'm now looking for a role where I can work on a larger product with a strong design system, which is exactly what drew me to this position.

  • Why should we hire you?

    BeginnerHR

    What the interviewer is evaluating

    Whether you understand the role and can match your strengths to its needs with evidence.

    Key points a strong answer covers

    • Role's needs. Show you understand what the role needs.
    • Matching strengths. Match two or three strengths to those needs.
    • Evidence. Back each with evidence.
    • Enthusiasm. Close with genuine enthusiasm.

    Suggested answer structure

    1. Name the two or three things the role needs most.
    2. Match each with your experience and evidence.
    3. Add what makes you different.
    4. Finish with genuine interest.

    Common mistakes

    • Generic claims like 'I'm hardworking' with no evidence.
    • Comparing yourself to other candidates you don't know.

    Likely follow-up questions

    • What would you do in your first 90 days?
    • What's one area where you'd need support?
    Example strong answer

    From the job description and our conversation, you need someone who can take ownership of the customer onboarding process, work with sales and product, and improve the numbers. I've done exactly that for three years: at my current company I redesigned onboarding for new accounts and cut the time to first value from 14 days to 6. I'm comfortable working across teams — I run a weekly session with sales and product on customer feedback — and I'm very data-driven, so I'd measure everything from day one. I'm also genuinely excited about your product, because it solves a problem I've seen customers struggle with.

  • Tell me about a time you disagreed with a teammate. How did you handle it?

    BeginnerBehavioural

    What the interviewer is evaluating

    Handling conflict constructively and keeping relationships.

    Key points a strong answer covers

    • Listened to their view. Show you listened to understand their view.
    • Used facts / common goal. Bring it back to facts or a shared goal.
    • Resolution & relationship. Resolve it and keep the relationship.

    Suggested answer structure

    1. Situation — one or two sentences of context.
    2. Task — what you were responsible for.
    3. Action — what you did, step by step (say “I”).
    4. Result — what changed, with a number if you can back it up.
    5. Reflection — what you learned or would do differently.

    Common mistakes

    • Making the other person the villain.
    • A story where you were simply right and they gave in.

    Likely follow-up questions

    • What if you couldn't reach agreement?
    • Have you ever been wrong in a disagreement?
    Example strong answer (a fictional story — use your own)

    On a website rebuild, a senior designer wanted an animated, image-heavy homepage, and I was worried it would hurt mobile load times and SEO. As the developer responsible for performance, I needed us to agree before the sprint started. I asked her to walk me through what she was trying to achieve — she wanted the brand to feel premium. I built two quick prototypes, one with her full design and one with lighter animations, and we tested both on a mid-range phone together. Hers took nearly six seconds to load. We agreed on a version that kept the key animation but lazy-loaded the rest. The page launched loading in under two seconds, and she later asked me to review designs earlier. I learned that testing together beats debating.

  • Tell me about a mistake you made and what you learned.

    BeginnerBehavioural

    What the interviewer is evaluating

    Honesty, accountability and learning.

    Key points a strong answer covers

    • Real mistake owned. Own a real mistake.
    • Fixed it. Show how you fixed it and who you told.
    • Changed behaviour. Show what you changed afterwards.

    Suggested answer structure

    1. Situation — one or two sentences of context.
    2. Task — what you were responsible for.
    3. Action — what you did, step by step (say “I”).
    4. Result — what changed, with a number if you can back it up.
    5. Reflection — what you learned or would do differently.

    Common mistakes

    • Choosing a fake mistake like 'I work too hard'.
    • Blaming others.

    Likely follow-up questions

    • How did your manager react?
    • How do you know you haven't repeated it?
    Example strong answer (a fictional story — use your own)

    In my first year as a marketing coordinator, I sent a promotional email to our whole list with the wrong discount code — I'd tested the email but not clicked the code itself. Within an hour customers were complaining that it didn't work. I told my manager immediately, set the wrong code to apply the discount too, and sent a short correction email with an apology. We lost very little revenue, and some customers replied thanking us for the quick fix. Since then I use a pre-send checklist that includes testing every link and code as a customer would, and I asked for a second person to check any campaign to more than 10,000 people.

  • Describe a situation where you worked under pressure or to a tight deadline.

    BeginnerBehavioural

    What the interviewer is evaluating

    Prioritisation, composure and delivery.

    Key points a strong answer covers

    • The pressure. Make the pressure concrete.
    • Prioritised. Show how you prioritised.
    • Communicated. Show how you kept people informed.
    • Delivered. Show the outcome.

    Suggested answer structure

    1. Situation — one or two sentences of context.
    2. Task — what you were responsible for.
    3. Action — what you did, step by step (say “I”).
    4. Result — what changed, with a number if you can back it up.
    5. Reflection — what you learned or would do differently.

    Common mistakes

    • Glorifying working all night as the solution.
    • No mention of prioritising.

    Likely follow-up questions

    • What would you do if it was clear you couldn't make the deadline?
    • How do you stop pressure affecting quality?
    Example strong answer (a fictional story — use your own)

    Two days before a client presentation, our analyst fell ill and I had to finish the market research report she'd been leading. I listed everything left and asked the account director which sections the client cared about most — pricing and competitor comparison. I focused on those, reused verified data from our previous report, and moved the appendix to a follow-up email. I sent a short update each evening so nobody was surprised. We delivered the core report on time, the client approved the next phase, and the appendix followed two days later. I learned to ask early what matters most rather than trying to do everything equally well.

  • What would you do if you realised you were going to miss a deadline?

    BeginnerSituational

    What the interviewer is evaluating

    Transparency and problem solving.

    Key points a strong answer covers

    • Tell people early. Flag it as soon as you know.
    • Assess the gap. Work out how far off you are.
    • Options. Offer options: reduced scope, help, a new date.
    • Prevent repeats. Learn why it happened.

    Suggested answer structure

    1. Clarify the situation and what's at stake.
    2. Say what you'd do first, and why.
    3. Explain who you'd involve and how you'd communicate.
    4. Describe how you'd check the outcome and prevent a repeat.

    Common mistakes

    • Waiting until the deadline to say anything.
    • Promising you'll just work all night.

    Likely follow-up questions

    • What if your manager is unavailable?
    • Has this happened to you?
    Example strong answer

    I'd tell the person depending on it as soon as I realised, not at the deadline. Before that conversation I'd work out how far off I am and why, so I could offer options: delivering the most important part on time and the rest a few days later, getting help from a colleague, or agreeing a new date. Then I'd let them decide what works best for them, and keep them updated. Afterwards I'd look at why it slipped — usually underestimating something — so I plan better next time.

Ready to answer them out loud?

Run a timed java developer mock interview, type or speak your answers, and get a score breakdown with what to improve.

Interview questions for related roles