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.
Why must you override hashCode when you override equals in Java?
BeginnerTechnicalPractise this question and get feedbackWhat 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
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- 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 samehashCode. Hash-based collections rely on it:HashMapandHashSetuse the hash code to pick a bucket and only then callequalswithin that bucket. If I overrideequalsso twoEmailobjects with the same address are equal but leave the default identityhashCode, 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.2.
Compare ArrayList, LinkedList, HashMap and TreeMap.
BeginnerTechnicalPractise this question and get feedbackWhat 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
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- 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
ArrayListis backed by an array: O(1) access by index and amortised O(1) appends, and it's cache-friendly — my default list.LinkedListis a chain of nodes: O(n) to reach an index, and despite its reputation for cheap inserts it's rarely faster in practice; for queuesArrayDequeis better.HashMapgives O(1) average lookups with no ordering guarantee;LinkedHashMapkeeps insertion order — handy for an LRU cache.TreeMapkeeps keys sorted using a red-black tree, with O(log n) operations and range queries likeheadMap. For concurrent access I useConcurrentHashMaprather than synchronising a HashMap.3.
Describe JVM memory: the heap, the stack and garbage collection.
IntermediateTechnicalPractise this question and get feedbackWhat 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
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- 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 anOutOfMemoryErrorI capture a heap dump and analyse it with Eclipse MAT or VisualVM.4.
How do you write thread-safe code in Java?
AdvancedTechnicalPractise this question and get feedbackWhat 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
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- 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:
synchronizedor aReentrantLockfor compound operations,volatileonly for visibility of a simple flag — it doesn't makecount++atomic — andAtomicIntegerorLongAdderfor counters. I lean onjava.util.concurrent:ConcurrentHashMap, executors instead of raw threads,CompletableFuturefor 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.5.
How does dependency injection work in Spring Boot?
IntermediateTechnicalPractise this question and get feedbackWhat 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
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- 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,@Repositoryor@RestControllerare found by component scanning, and@Beanmethods in@Configurationclasses define others, like third-party clients. I use constructor injection with final fields — with a single constructor no@Autowiredis 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.6.
How does @Transactional work in Spring, and what are its pitfalls?
AdvancedTechnicalPractise this question and get feedbackWhat 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
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- 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
@Transactionalis 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 setrollbackFor. Propagation decides whether a method joins the existing transaction or starts a new one withREQUIRES_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.7.
Explain Java Streams. When would you use them, and when not?
IntermediateTechnicalPractise this question and get feedbackWhat 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
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- 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 ascollect,toListorcount, 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 forparallelStreamby 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.8.
What's the difference between checked and unchecked exceptions in Java?
BeginnerTechnicalPractise this question and get feedbackWhat 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
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- 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
Exceptionbut notRuntimeException, likeIOException— must be caught or declared withthrows; the compiler enforces it. Unchecked exceptions extendRuntimeException—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.9.
How would you build and structure a REST API with Spring Boot?
IntermediateTechnicalPractise this question and get feedbackWhat 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
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- 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.
@RestControllerclasses handle HTTP — mapping with@GetMapping/@PostMapping, binding request DTOs with@Validso Bean Validation rejects bad input — and delegate to@Serviceclasses that hold business logic and transactions. Spring Data JPA repositories handle persistence, and I accept aPageablefor 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@RestControllerAdvicemaps exceptions to consistentProblemDetailresponses. springdoc generates OpenAPI documentation, and Actuator exposes health and metrics.10.
What is Optional in Java, and how should it be used?
BeginnerTechnicalPractise this question and get feedbackWhat 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
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- 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 likefindByIdcan make 'not found' explicit in its type instead of returning null. It's designed mainly for return types. Callers then use its API —mapto transform,orElseororElseGetfor a default,orElseThrowto turn absence into an exception — rather than callingget()unchecked, which just recreates the NullPointerException. I don't use it for fields, parameters or collections; an empty list is better thanOptional<List>. One subtlety:orElsealways evaluates its argument, whileorElseGetonly calls the supplier when needed.
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.