Every Java interview question on this site
1100 questions, gathered from all five places they live — the reference curriculum, the release catalogue, the company-type breakdowns, and the follow-ups and self-checks inside every written entry. A green dot means the answer is written.
- Questions
- 1100
- Answered
- 286
- Sources
- 5
- Duplicates folded
- 133
This list is derived, never authored. Every question here is read from the file that owns it, so adding one anywhere puts it on this page at the next build and there is no second copy to fall out of date. The same question asked in two places is folded into one — 133 of them were.
1100 questions
Build and delivery · CI and delivery
- How do you handle secrets in a pipeline?asked most
- How do you roll back a bad release?
- What is a canary release, and what do you watch during one?
- What is a feature flag for, and what does it cost?
- What makes a change hard to roll back?
- What should be allowed to fail a build?
- What stages would you put in a pipeline, and in what order?
- Where should environment-specific configuration live?
- Why should the same artifact go to every environment?
Build and delivery · Dependency management
- A scanner reports a critical CVE in a transitive dependency. What now?
- How do you find out why a dependency is on your classpath?
- How do you keep dependencies current without breaking things?
- How do you know whether your dependencies have known CVEs?
- Should you use version ranges or pinned versions?
- Two libraries need different versions of the same dependency. What happens?asked most
- What does a reproducible build require?
- What is an SBOM for?
- What is NoSuchMethodError telling you?
Build and delivery · Maven and Gradle
- How do you speed up a slow build?
- Maven or Gradle, and what is the real difference?
- What are the Maven lifecycle phases, in order?
- What does the provided scope mean, and when do you use it?
- What is a BOM, and what problem does it solve?
- What is the difference between implementation and api in Gradle?
- What is the difference between install and package?
- When is a multi-module build worth it?
- Why does a test-only library end up in the jar?
Build and delivery · Packaging and containers
- How does the JVM decide its heap size in a container?
- How would you cut a Spring Boot application's startup time?
- What is a distroless or slim base image, and what do you lose?
- What is a native image, and what does it give up?
- What is inside an executable Spring Boot jar?
- Which GC would you pick for a small container?
- Why is the first request after a deploy slow?
- Why layer a Docker image, and what goes in which layer?
- Your container is OOM-killed but the heap looks fine. Why?asked most
Core Java · Collections
- Arrays.asList vs List.of vs unmodifiableList?
- Comparable vs Comparator, and what makes an ordering legal?
- Does an unmodifiable list protect its elements?
- HashMap vs Hashtable vs ConcurrentHashMap?asked most
- HashSet vs LinkedHashSet vs TreeSet?
- How do you choose between a List, a Set and a Map?
- How do you remove elements while iterating?
- How does ArrayList grow, and does it ever shrink?
- How does HashMap work internally?asked most
- How is HashSet implemented?
- Is PriorityQueue iteration in sorted order?
- What did SequencedCollection add in Java 21?
- What does load factor actually control?
- What happens when a map key's hash changes?asked most
- What is a defensive copy and when do you need one?
- What is a fail-fast iterator, and when does it fail to fail?
- What is CopyOnWriteArrayList for?
- What is the difference between add and offer, remove and poll?
- What is the difference between fail-fast and weakly consistent?
- When do you need a TreeMap, and what does it cost?
- When would you use LinkedList instead of ArrayList?asked most
- Why can a TreeSet contain two objects that are equals()?
- Why is Map not a Collection?
- Why use ArrayDeque instead of Stack or LinkedList?
Core Java · Concurrency
- AtomicInteger, synchronized, or ReentrantLock?
- Do virtual threads make thread pools obsolete?
- How do you compose asynchronous work with CompletableFuture?
- How do you handle a failure in a CompletableFuture chain?
- How do you size and shut down a thread pool?asked most
- How does ConcurrentHashMap achieve thread safety?asked most
- How does ThreadLocal leak memory in a thread pool?
- Is double-checked locking safe?
- Is HashMap thread-safe on modern Java?asked most
- Runnable vs Callable?
- What are the states in a thread's lifecycle?
- What are virtual threads, and when do they not help?
- What causes a deadlock and how do you prevent it?asked most
- What does the JMM guarantee about final fields?
- What does volatile guarantee, and what does it not?asked most
- What happens when a thread pool's queue is full?
- What is a race condition, precisely?
- What is the difference between start() and run()?
- What is the difference between synchronized and ReentrantLock?
- What is the difference between thenApply and thenApplyAsync?
- What is the happens-before relationship?asked most
- What is thread pinning?
- What is ThreadLocal legitimately used for?
- When would you use a BlockingQueue?
- Why is count++ not thread-safe?asked most
- Why is Executors.newFixedThreadPool risky by default?
Core Java · Dates and time
- How should you store a timestamp in a database?
- What happens to a local time during a DST transition?
- What is the difference between a ZoneId and a ZoneOffset?
- What is the difference between Duration and Period?
- What was wrong with Date and Calendar?
- When do you use LocalDateTime versus Instant versus ZonedDateTime?
- Why are java.time types immutable?
- Why is SimpleDateFormat not thread-safe?
Core Java · Exceptions
- How do you debug a NullPointerException on a chained call?
- How do you design a custom exception?
- Should you use exceptions for control flow?
- What does try-with-resources do that finally cannot?asked most
- What is a suppressed exception?
- What is Objects.requireNonNull for?
- What is the difference between an Error and an Exception?
- What is the difference between checked and unchecked exceptions?asked most
- When is it right to make an exception checked?
- When should a method return Optional instead of null?asked most
- Why does exception chaining matter?
- Why is an empty catch block worse than no try at all?
Core Java · Functional Java
- How do Collectors.groupingBy and toMap differ in failure modes?
- How do you handle a checked exception inside a stream?
- How do you write a custom collector?
- How is a lambda different from an anonymous inner class?
- Should you use a stream when you need early exit?
- What are the four kinds of method reference?
- What does flatMap do?
- What happens when two interfaces provide the same default method?
- What makes an interface functional?
- What makes an operation safe to parallelise?
- When is parallelStream() a mistake?
- Why does a stream with no terminal operation do nothing?asked most
- Why were default methods added, and what did they break?
Core Java · Generics
- What can you do with a List<?>
- What does <T extends Comparable<T>> mean?
- What is a generic method, and when is one needed?
- What is a raw type and why does using one disable generics everywhere?
- What is heap pollution?
- What is PECS?
- What is type erasure, and what does it prevent?asked most
- Why can't a class implement both Comparable<A> and Comparable<B>?
- Why can't you create new T[] or call instanceof T?
- Why is a generic varargs parameter unsafe?
- Why is List<String> not a List<Object>?asked most
- Why use generics instead of Object?
Core Java · I/O and files
- How do you read a large file without loading it into memory?
- What does buffering actually change?
- What does Files.lines return, and why must you close it?
- What does transient do?
- What is serialVersionUID for?
- What is the difference between InputStream and Reader?
- Why is Java serialization considered dangerous?
- Why must you always specify a charset?
- Why use Path and Files instead of File?
Core Java · JVM and memory
- Does calling System.gc() do anything?
- How do you benchmark Java code correctly?
- How do you diagnose high CPU in a running JVM?
- How do you find a leak from a heap dump?
- How do you get a memory leak in a garbage-collected language?asked most
- How do you read a thread dump?
- How does garbage collection decide what to collect?asked most
- What are strong, soft, weak and phantom references for?
- What causes StackOverflowError versus OutOfMemoryError?
- What does the JIT compiler do?
- What happens when a class is loaded?
- What is a ClassLoader leak?
- What is a stop-the-world pause?
- What is warm-up, and how long does it take?
- What lives on the heap and what lives on the stack?asked most
- What replaced PermGen, and why?
- When exactly does a static initialiser run?
- Which garbage collector should you use, and how would you decide?
- Why is your first benchmark result wrong?
Core Java · Language basics
- Does var make Java dynamically typed?
- How do you copy an array, and what does shallow mean here?
- Is Java pass-by-value or pass-by-reference?asked most
- What are the eight primitive types and their sizes?
- What can you switch on, and what has changed by version?
- What do Double.NaN and Infinity compare equal to?
- What does 5 / 2 evaluate to, and why?
- What does i++ + ++i evaluate to?
- What happens when an int overflows?
- What happens when you unbox a null Integer?
- What is autoboxing, and where does it cost you performance?
- What is the default value of an array element?
- What is the difference between & and &&?
- What is the difference between a primitive and a reference variable?asked most
- What is the difference between a switch statement and a switch expression?
- What should you use for money, and why not double?asked most
- Where can you use var, and where can you not?
- Where do primitives and objects actually live in memory?
- Why does == work for Integer 127 but not 128?asked most
- Why does Object[] a = new String[1]; a[0] = 1; compile but fail at runtime?
- Why does switch fall through, and when is that useful?
- Why is 0.1 + 0.2 not equal to 0.3?asked most
- Why is char 16 bits, and what does that mean for emoji?
Core Java · Modern Java
- How has pattern matching changed instanceof and switch?
- What breaks when you move from Java 8 to 17 or 21?
- What did JPMS actually change for application developers?
- What do sealed classes enable that abstract classes cannot?
- What is exhaustiveness, and why does it matter?
- What is the difference between LTS and feature releases?
- Which Java version should a new project use?
- Why does setAccessible fail on a JDK class now?
Core Java · Objects and OOP
- Can a constructor be private, and why would you do that?
- Can an enum implement an interface or have a constructor?
- Can an interface have state?
- Can you override a static method?
- Can you validate a record's components?
- How do you make a class genuinely immutable?asked most
- How does an anonymous inner class leak memory?
- How does dynamic dispatch work?
- In what order do fields, initialisers and constructors run?
- What are the four access modifiers and when do you use each?
- What belongs in toString(), and what must never?
- What can a record not do?
- What does immutability buy you at runtime?
- What is an effectively final variable, and why does capture need it?
- What is constructor chaining, and when do you need this()?
- What is covariant return type?
- What is encapsulation actually for?
- What is the contract between hashCode() and equals()?asked most
- What is the difference between a static nested class and an inner class?
- What is the difference between overloading and overriding?asked most
- What problem do default methods solve, and what did they reintroduce?
- When do you choose an abstract class over an interface?asked most
- When should you use a record instead of a class?asked most
- Why are fields not polymorphic?
- Why is a final field holding a List still mutable?
- Why is a public getter that returns a mutable list a bug?
- Why is an enum better than a set of int constants?
- Why is an enum the recommended way to write a singleton?
- Why is clone() considered broken?
- Why should you prefer composition over inheritance?
Core Java · Strings
- How do you join a collection with a delimiter?
- How does switch on a String work internally?
- How is indentation stripped from a text block?
- Is Pattern thread-safe? Is Matcher?
- String.format, concatenation or a template — which and why?
- What does intern() do, and where does the pool live now?
- What is catastrophic backtracking?
- What is the difference between a char, a code point and a grapheme?
- What is the difference between String, StringBuilder and StringBuffer?asked most
- What problem do text blocks solve, and what are the traps?
- Why is String immutable, and what is the string pool?asked most
- Why must you always specify a charset when converting bytes?
- Why should you compile a Pattern once and reuse it?
- Why should you never compare strings with ==?asked most
Data structures and algorithms · Arrays and strings
- Check whether two strings are anagrams.
- Detect a cycle in a linked list, and find where it starts.
- Find two numbers in a sorted array that sum to a target.asked most
- Longest substring without repeating characters.asked most
- Maximum sum subarray of size k.
- Remove duplicates from a sorted array in place.
- Reverse the words in a sentence, in place where possible.
- When does a sliding window not apply?
- Why is building a string in a loop with plus a problem?asked most
Data structures and algorithms · Complexity analysis
Data structures and algorithms · Hashing
- Find the first non-repeating character in a string.
- Group anagrams together.
- How would you design a hash function for a custom key?
- Two sum, unsorted, in one pass.asked most
- What happens if you mutate a key after inserting it?
- What is the worst case of a HashMap lookup, and when does it happen?asked most
Data structures and algorithms · Lists, stacks and queues
- ArrayList or LinkedList, and why is the textbook answer usually wrong?asked most
- Find the k largest elements in a stream.asked most
- How does PriorityQueue order its iteration?
- Implement a queue using two stacks.
- Merge k sorted lists.
- Merge two sorted lists.
- Reverse a linked list, iteratively and recursively.asked most
- Validate balanced brackets in an expression.asked most
- What should you use instead of java.util.Stack, and why?
Data structures and algorithms · Recursion, DP and greedy
- Generate all subsets, or all permutations, of a list.
- Give an example where greedy fails and DP succeeds.
- How deep can Java recurse, and what happens then?
- Memoisation or tabulation?
- Schedule the maximum number of non-overlapping intervals.
- Solve the coin change problem and state its complexity.
- Solve the n-queens problem, and say what makes it backtracking.
- What tells you a problem is dynamic programming?asked most
- When is a greedy choice provably correct?
Data structures and algorithms · Searching and sorting
- Comparable or Comparator?
- Find the first element greater than a target.
- How do you binary search on an answer rather than an array?
- How do you sort by two fields, one descending?
- Implement binary search, and say where the off-by-one lives.asked most
- Quick sort or merge sort?
- What does a stable sort guarantee, and when do you need it?
- Which sort does Arrays.sort use, and why does it depend on the type?
- Why does sorting sometimes throw about a general contract violation?
Data structures and algorithms · Trees and graphs
- BFS or DFS — how do you choose?asked most
- Detect a cycle in a directed graph.
- Find the lowest common ancestor of two nodes.
- How do you check whether a tree is a valid BST?
- How would you order tasks with dependencies?
- In-order, pre-order and post-order — when does each matter?
- Print a binary tree level by level.asked most
- What is a balanced tree, and why does it matter?
- Where does the JDK use a red-black tree?
Databases and persistence · Indexing
- Does an index on (a, b) help a query filtering only on b?asked most
- How do you choose the column order in a composite index?
- How do you find out why a query is slow?asked most
- How does a database index actually work?asked most
- Is a sequential scan always bad?
- Is an index on a boolean column useful?
- What is a covering index?
- What is cardinality, and why does the planner care?
- What is the difference between a clustered and a non-clustered index?
- What is the difference between a seq scan, an index scan and an index-only scan?
- Why does an index make writes slower?
- Why would the database ignore an index you created?asked most
Databases and persistence · JPA and Hibernate
- JOIN FETCH, entity graph, or batch size — which and when?
- save() versus persist() versus merge()?
- Should you return a JPA entity from a REST controller?asked most
- What are the entity lifecycle states?
- What are the fetch types, and which is the default for each mapping?asked most
- What are the requirements for a JPA entity class?
- What is dirty checking, and why did my entity save without a save() call?asked most
- What is the N+1 problem, and how do you detect it?asked most
- When is the second-level cache a mistake?
- When should you drop to native SQL?
- Which side owns a bidirectional relationship, and why does it matter?
Databases and persistence · NoSQL and caching
- How do you choose between strong and eventual consistency?
- What breaks when the cache and the database disagree?
- What caching pattern would you use, and how do you invalidate?asked most
- What does CAP actually say, and what does it not?
- What does read-your-own-writes mean, and why do users notice?
- What is a cache stampede, and how do you prevent it?
- When would you not use a relational database?
Databases and persistence · Performance and operations
- A query is slow in production but fast locally. Why?asked most
- How do you find the queries worth optimising?
- How do you size a database connection pool?asked most
- Is SELECT * ever acceptable?
- What happens when the pool is exhausted?
- What is keyset pagination, and what does it give up?
- Why does moving to virtual threads make pool sizing more urgent?
- Why does OFFSET pagination get slower on later pages?asked most
Databases and persistence · Schema design
- Flyway or Liquibase, and why version migrations at all?
- How do you change a schema with zero downtime?asked most
- Natural key or surrogate key?
- Should validation live in the application or the database?
- Should you use UUIDs as primary keys?
- What are the normal forms, and where do you stop in practice?
- What does a foreign key actually enforce, and what does it cost?
- What happens to a UNIQUE constraint with NULL values?
- When would you denormalise on purpose?
- Why should a migration never be edited after it has run?
Databases and persistence · SQL fundamentals
- How do you compare a column against NULL correctly?
- How do you find rows in A with no match in B?
- How do you update rows based on another table?
- How does COUNT(*) differ from COUNT(column)?
- What does a CROSS JOIN produce, and when is it deliberate?
- What does an aggregate do with NULL values?
- What is the difference between a correlated and an uncorrelated subquery?
- What is the difference between an INNER JOIN and a LEFT JOIN?asked most
- What is the difference between DELETE, TRUNCATE and DROP?
- What is the difference between WHERE and HAVING?asked most
- When does a window function beat a GROUP BY?
- Why is NULL = NULL not true?asked most
- Why must every non-aggregated column appear in GROUP BY?
- Write a query to find the second-highest salary.asked most
Databases and persistence · Transactions and isolation
- How do you maintain consistency across two services?
- How is atomicity actually implemented?
- Optimistic versus pessimistic locking — when do you use each?
- What are the isolation levels, and what does each permit?asked most
- What causes a database deadlock, and how do you prevent it?asked most
- What does ACID stand for, and which part does isolation level weaken?asked most
- What does SELECT ... FOR UPDATE do?
- What is a non-repeatable read versus a phantom read?
- What is the outbox pattern, and what problem does it solve?
- Which isolation level does your database default to?asked most
Design patterns · Behavioural patterns
- How do Spring application events relate to this?
- How do you pick a strategy by configuration?
- How would you replace a long if-else chain over a type?
- Is a lambda a strategy?
- Synchronous or asynchronous listeners?
- What are the risks of the observer pattern?
- What is chain of responsibility, and where have you used one?
- When is a command object worth the indirection?
- Where does Spring use the template method pattern?
Design patterns · Creational patterns
- Do records remove the need for builders?
- Factory method or abstract factory — what is the difference?
- How do you implement a thread-safe singleton?asked most
- How does a builder help with immutability?
- How is a Spring singleton bean different from a singleton?
- What problem does a factory solve that a constructor does not?
- When is a builder better than a constructor?
- Where does the JDK use a factory method?
- Why is an enum singleton the safest form?
Design patterns · SOLID and design judgement
- Explain the single responsibility principle with an example from your code.asked most
- How do you refactor safely without tests?
- What breaks the Liskov substitution principle?
- What does the open-closed principle mean in practice?
- What is a service locator, and why is it worse than injection?
- What is an anemic domain model, and is it always wrong?
- What is dependency inversion, and how is it different from dependency injection?
- What tells you a class is doing too much?
- When do you leave bad code alone?
- When is a design pattern the wrong answer?
- Why prefer several small interfaces over one large one?
Design patterns · Structural patterns
- Adapter or facade — how do you tell them apart?
- How would you integrate a third-party library you might replace?
- What is an anti-corruption layer?
- What is the difference between a proxy and a decorator?
- Where does Java use the flyweight pattern?
- Where does Spring use the proxy pattern?asked most
- Where does the JDK use decorators?
- Where would a composite structure be the right model?
Microservices and APIs · Data across services
- Choreography or orchestration?
- How do you build a screen that needs data from four services?
- How do you handle a transaction that spans three services?asked most
- Is a shared database between two services ever acceptable?
- What does CAP actually say, and how is it usually misquoted?
- What is CQRS, and when is it worth the complexity?
- What is eventual consistency, and how do you design a UI around it?
- What makes a good compensating action?
- When do you genuinely need strong consistency?
Microservices and APIs · Messaging and events
- Event notification or event-carried state transfer?
- How do you handle a message that keeps failing?
- How do you publish an event and commit a row atomically?asked most
- How do you version an event schema?
- How do you write a consumer that tolerates duplicates?asked most
- How does Kafka give you ordering, and where does it stop?
- Should an event be a command or a fact?
- What do at-least-once and exactly-once actually mean?asked most
- What happens to ordering when you add consumers?
- What is the outbox pattern, and what does it cost?
- When would at-most-once be the right choice?
- Why not use a distributed transaction across the two?
Microservices and APIs · Observability
- How do you decide between INFO, WARN and ERROR?
- How do you follow one request across ten services?asked most
- What are the four golden signals?
- What is the difference between a liveness and a readiness probe?
- What is the difference between a trace, a span and a correlation id?
- What makes a log line useful in production?
- What should never appear in a log?
- Why do you alert on percentiles rather than averages?
- Why is sampling necessary, and what does it lose?
Microservices and APIs · Resilience patterns
- How do you degrade a page when one section's service is down?
- How do you pick the thresholds?
- What can go wrong with a naive retry?asked most
- What does a circuit breaker actually do?asked most
- What is a bulkhead, and what does it protect?
- What is a cascading failure, and how do you stop one?
- What is a good fallback, and what is a dangerous one?
- Which failures should never be retried?
- Why does backoff need jitter?
Microservices and APIs · REST and API design
- How do you avoid leaking internals in an error?
- How do you make a POST endpoint safe to retry?asked most
- How do you remove a field that a client might still read?
- How do you stop an endpoint returning a hundred megabytes?
- How do you version an API, and which approach would you pick?
- Offset pagination or cursor pagination?
- Should a failed business rule be a 200 with an error body?
- Should the API let a client choose which fields come back?
- What belongs in an error response?
- What happens when a retry arrives while the first request is still running?
- What is RFC 7807 problem detail, and is it worth adopting?
- What makes an API RESTful, beyond using HTTP?
- When would you return 400 versus 422, and 401 versus 403?
- Where should the idempotency key come from, and how long do you keep it?
- Which changes are backwards compatible and which are not?
- Which HTTP methods are safe, and which are idempotent?asked most
Microservices and APIs · Service communication
- Client-side or server-side load balancing?
- How do you choose a timeout value?
- How do you evolve a protobuf message without breaking clients?
- How does a chain of synchronous calls turn one slow service into an outage?
- How does a service find another service's address?
- REST or gRPC for internal service-to-service calls?
- What does an API gateway do that a load balancer does not?
- What is a connection pool, and what happens when it is exhausted?
- What is the availability of a request that touches five services synchronously?
- What is the default timeout on your HTTP client?asked most
- What problem does GraphQL solve, and what does it cost?
- When would you use messaging instead of a REST call?asked most
Security · Authentication
- How do you handle a credential-stuffing attack?
- How do you revoke a JWT before it expires?
- How do you scale sessions across many instances?
- How should a password be stored?asked most
- Session cookies or JWTs?asked most
- Walk me through the authorisation code flow.
- What is inside a JWT, and what protects it?asked most
- What is the alg none attack?
- What is the difference between OAuth 2 and OpenID Connect?
- Where should a browser store a token?
- Why is a salt necessary, and what does a pepper add?
- Why is PKCE needed for public clients?
Security · Authorisation
Security · Common web vulnerabilities
- Does using JPA make you safe from injection?
- How do you handle untrusted input safely instead?
- How do you prevent SQL injection?asked most
- How do you prevent XSS properly?
- What is SSRF, and why is it worse in a cloud environment?
- What is the difference between XSS and CSRF?
- What other kinds of injection affect a Java service?
- Why does a stateless API often not need CSRF protection?
- Why is Java deserialisation dangerous?asked most
Security · Crypto, secrets and dependencies
- How do you reduce supply-chain risk in a Java service?
- How do you rotate a key without downtime?
- Should service-to-service traffic inside a private network use TLS?
- What is at rest versus in transit encryption?
- What is the difference between symmetric and asymmetric encryption?
- What was Log4Shell, and what did it teach?
- When would you hash and when would you encrypt?
- Where do secrets belong, and what do you do when one leaks?asked most
- Why should you never write your own crypto?
Spring and Spring Boot · Spring AOP
- How does Spring AOP work, and what are its limits?asked most
- JDK dynamic proxy versus CGLIB — when does Spring pick which?
- What are a join point, a pointcut and advice?
- What thread pool does @Async use by default?
- When would you write a custom aspect rather than use a library one?
- Why does @Async silently run synchronously sometimes?
- Why does a final method break AOP?
Spring and Spring Boot · Spring Boot
- @Value versus @ConfigurationProperties?
- How do profiles work, and what are their traps?
- How do you exclude or override an auto-configuration?
- How do you see which auto-configurations were applied?
- How do you switch from Tomcat to Undertow or Jetty?
- How does Boot decide dependency versions?
- How does Spring Boot auto-configuration actually work?asked most
- What does the health endpoint actually check?
- What happens between main() and the first request being served?
- What is in a Spring Boot starter?
- What is the precedence order for Spring Boot configuration?
- Which actuator endpoints are dangerous to expose?
Spring and Spring Boot · Spring core and dependency injection
- @PostConstruct versus InitializingBean versus @Bean(initMethod)?
- How do you inject a dependency without Spring at all?
- How do you inject a prototype bean into a singleton?
- How do you resolve two beans of the same type?
- How does component scanning decide what to pick up?
- What are request and session scopes, and how are they implemented?
- What are the phases of a bean's lifecycle?
- What happens on a circular dependency, and how do you fix it?asked most
- What is a BeanPostProcessor, and what uses one?
- What is inversion of control, and how is it different from dependency injection?asked most
- What is the default bean scope, and why does it matter?asked most
- What is the difference between @Component, @Service and @Repository?asked most
- When do you use @Bean instead of @Component?
- Why does constructor injection expose cycles that field injection hides?
- Why is constructor injection preferred over field injection?asked most
Spring and Spring Boot · Spring Data and transactions
- CrudRepository versus JpaRepository?
- How do you fix N+1 — join fetch, entity graph, or batch size?
- How does @Transactional actually work?asked most
- How does Spring Data implement a repository interface you never wrote?asked most
- What causes LazyInitializationException?asked most
- What do propagation and isolation levels control?
- What does the persistence context cache, and for how long?
- What is the N+1 query problem, and how do you detect it?asked most
- When do you write @Query instead of a derived method name?
- Which exceptions trigger a rollback by default?asked most
- Why does @Transactional not work on a private or self-invoked method?asked most
- Why does making everything EAGER make it worse?
- Why should an entity not be returned from a controller?
Spring and Spring Boot · Spring MVC and REST
- @Controller versus @RestController?
- @RequestParam versus @PathVariable versus @RequestBody?
- How do you handle exceptions across all controllers?asked most
- How do you return a consistent error body?
- How do you version a REST API?
- How does @Valid work, and where does the validation happen?
- How is the request body converted into an object?
- Walk me through what happens when a request hits a Spring MVC application.asked most
- What does the DispatcherServlet do?
- What is ProblemDetail?
- What is the difference between a Filter and a HandlerInterceptor?
- Why does @Valid do nothing on a nested object sometimes?
Spring and Spring Boot · Spring Security
- How do you implement JWT authentication?
- How does @PreAuthorize work, and what are its limits?
- How does Spring Security intercept a request?asked most
- How is the authenticated user made available to your code?
- How should passwords be stored?
- Session versus token authentication — what changes?
- URL-based versus method-level authorization?
- Why does my @ControllerAdvice not catch a 403?
- Why is a salt not a secret?
Spring and Spring Boot · Testing Spring applications
- @Mock versus @MockBean — when does the difference matter?
- @SpringBootTest versus @WebMvcTest versus @DataJpaTest?asked most
- How do you test a transactional method's rollback behaviour?
- What should you not mock?
- When is @SpringBootTest the wrong choice?
- Why is the Spring test context cached, and when is it evicted?
- Why test against Testcontainers instead of H2?
System design · Caching
- Explain cache-aside, and what happens on a miss.asked most
- How do you invalidate a cache?asked most
- How long should a TTL be?
- Local cache or distributed cache?
- LRU or LFU?
- What hit rate makes a cache worth having?
- What is a cache stampede, and how do you prevent one?
- Where would you put a cache — client, CDN, service or database?
- Write-through or write-behind?
System design · Case studies
- Design a chat application.
- Design a job scheduler that survives restarts.
- Design a leaderboard.
- Design a metrics ingestion pipeline.
- Design a news feed.asked most
- Design a notification service that must not send twice.
- Design a product catalogue with search and filters.
- Design a rate limiter as a shared service.
- Design a URL shortener.asked most
System design · Data storage at scale
- Active-active or active-passive?
- How do you route reads to replicas safely?
- How would you shard this data, and what key would you choose?asked most
- SQL or NoSQL for this system, and why?asked most
- Synchronous or asynchronous replication?
- What becomes hard once data is sharded?
- What changes when you add a second region?
- What does a time-series or a graph store give you that a relational one does not?
- What is a hot partition, and how do you fix one?
- What is replication lag, and what breaks because of it?asked most
- What is your RPO and RTO, and how would you meet them?
- When would you add a search index rather than query the database?
System design · Fundamentals
- Explain CAP without saying pick two.
- Give an example where you would choose consistency over availability.
- Walk me through how you would start a system design question.asked most
- What does PACELC add?
- What is tail latency amplification?
- What is the difference between a functional and a non-functional requirement here?
- What is the difference between latency and throughput?
- What makes a service stateless, and why does it matter?asked most
- What would you estimate before choosing a database?
- When does horizontal scaling stop being possible?
- Where does the bottleneck move after you scale the app tier?
- Why do you care about p99 rather than the mean?asked most
System design · Reliability and operations
- Blue-green or canary?
- How do you deploy a change with no downtime?
- How do you make a database migration reversible?asked most
- What availability target would you set, and what does it cost?
- What happens to this design when the database is unavailable?asked most
- What is an error budget for?
- What is graceful degradation here, concretely?
- What is the difference between an SLA, an SLO and an SLI?
- Where are the single points of failure in what you just drew?
System design · Traffic, limits and delivery
- How do you deploy a change when the old file is cached everywhere?
- How do you rate limit fairly across tenants?
- How would you implement a rate limiter?asked most
- Layer 4 or layer 7?
- What belongs on a CDN, and what must not?
- What do ETag and Cache-Control actually do?
- What is backpressure, and what happens without it?
- What is sticky session routing, and what does it cost you?
- Which load balancing algorithm would you choose, and why?
Testing · Integration testing
- How do you isolate tests that share a database?
- How do you keep container-based tests fast?
- How do you stop tests depending on each other's data?
- How do you test a REST controller without starting a server?
- How do you test code that depends on the current time?
- Shared fixtures or per-test data?
- What is the difference between a slice test and a full context test?
- When is an end-to-end test worth its cost?
- Why test against a real database rather than H2?
Testing · Mocks and test doubles
- Should you mock a repository or use an in-memory database?
- What does it mean when a test needs five mocks?
- What is a spy, and when is one justified?
- What is over-specification in a test?
- What is the difference between a mock and a stub?asked most
- When is verifying a call the right assertion?
- When would you use a fake instead of a mock?
- Why do mock-heavy suites break on refactoring?
- Why should you avoid mocking types you do not own?
Testing · Unit testing with JUnit
- How do you assert that a method throws?
- How much setup is too much in a test?
- How should a test be named?
- Should one test have several assertions?
- What changed between JUnit 4 and JUnit 5?
- What is a parameterised test, and when does it beat a loop?
- What is the arrange-act-assert pattern for?
- What makes a good assertion failure message?
- When does a new test instance get created, and why does that matter?
Testing · What to test, and how much
- Do you practise TDD, and when do you not?
- How do you test concurrent code at all?
- Is 100 percent coverage a good goal?
- Is it acceptable to retry a failing test automatically?
- What causes a flaky test, and how do you fix one?asked most
- What does branch coverage add over line coverage?
- What does TDD actually change about the code?
- What is the cost of a test nobody trusts?
- What is the difference between TDD and writing tests first?
- What is the testing pyramid, and where does it break down?
- What would you not write a test for?
- Your build takes 40 minutes. What do you do?
Collections · How does HashMap work internally?
- A `HashMap` with default settings. How many `put()` calls with distinct keys before the table becomes 32?
- Difference between HashMap and ConcurrentHashMap iteration?
- Is HashMap thread-safe on Java 21? The infinite loop was fixed.
- Keys all return `hashCode() == 7`. After 8 inserts, what's in the bin?
- What breaks if hashCode() returns a constant?
- Why does mutating a key's hash-bearing field make the entry unreachable?
- Why is capacity always a power of two?
- You said it treeifies at 8. Always?
Collections · When would you use LinkedList instead of ArrayList?
- Both `ArrayList.add(i, e)` and `LinkedList.add(i, e)` are O(n). Why is one dramatically faster in practice?
- Difference between Arrays.asList and List.of?
- Does ArrayList ever shrink?
- Is iterating a LinkedList slow?
- LinkedList is better for insertions in the middle — agreed?
- Then when does LinkedList actually win?
- What did Java 21 change here?
- When is `LinkedList`'s O(1) insertion genuinely available to you?
- Which uses more memory?
- You need to add and remove at both ends, thousands of times a second. What do you use, and why not `LinkedList`?
Concurrency · How does ConcurrentHashMap achieve thread safety?
- `map.computeIfAbsent(k, x -> new ArrayList<>()).add(item)` — what is still wrong?
- Can you trust size()?
- ConcurrentHashMap or Collections.synchronizedMap?
- How did it work before Java 8?
- Is if (!map.containsKey(k)) map.put(k, v) safe on a ConcurrentHashMap?
- So what is the lock granularity now?
- What happens if you iterate while another thread writes?
- Where exactly is the lock taken on a write, and when is none taken at all?
- Why can't it hold null keys or values?
- Your cache uses `containsKey` then `put` and the database is seeing far more queries than there are distinct keys. Why, and what is the fix?
Concurrency · What does volatile guarantee, and what does it not?
- AtomicInteger or a lock, under heavy contention?
- Does a synchronized instance method exclude a synchronized static method in the same class?
- How do you fix it?
- So why is a volatile counter still broken?
- Two `synchronized` methods in one class. Name the case where they do not exclude each other.
- What does volatile guarantee?
- When is volatile the right tool?
- Why does `volatile` fix a `while (!shutdown)` loop but not a `count++`?
- Why does double-checked locking need volatile?
- Your integration test hammers the class with 50 threads and passes. What have you proved?
- Your test passes. Is the code thread-safe?
Concurrency · What is the happens-before relationship?
- `Settings` is immutable and its reference is `volatile`. A method reads `settings.endpoint` and `settings.timeoutMillis` on separate lines. What can go wrong?
- A field is written by main before `thread.start()` and read inside the thread. Does it need `volatile`?
- A producer writes five plain fields, then calls `latch.countDown()`. A consumer returns from `await()` and reads all five. Are they visible, and why?
- Do I need volatile on a field written before Thread.start()?
- How do you publish a configuration object safely?
- How would you prove code is free of a visibility bug?
- I added a sleep and the bug went away.
- Name the edges you actually use.
- What does final guarantee?
- What is happens-before?
- Why does transitivity matter?
Exceptions · What is the difference between checked and unchecked exceptions?
- Body throws `IOException`, `close()` throws `IllegalStateException`. What does the caller see, with and without try-with-resources?
- Can finally swallow an exception?
- How do you write a custom exception?
- Should you catch Error, or Throwable?
- What did Java 8 change about this?
- What happens if you catch InterruptedException and do nothing?
- What single fact determines whether an exception is checked?
- Which is better, checked or unchecked?
- Why does the arrival of lambdas count as an argument about checked exceptions?
- Why prefer try-with-resources over finally, beyond brevity?
Java8 · How do Collectors.groupingBy and toMap differ in failure modes?
- groupingBy with a boolean, or partitioningBy?
- How do groupingBy and toMap differ?
- How do you compute a min and a max in one pass?
- How would you get the highest-paid person in each department?
- What is a downstream collector?
- What map implementation does groupingBy return, and does the order matter?
- When is the two-argument `toMap` the right call?
- Why does `toMap` throw on a null value when the underlying map accepts one?
- Why does toMap reject a null value when HashMap accepts one?
- You group orders by a boolean and read `get(true)`. What can go wrong, and what would you use instead?
- Your toMap just threw in production. What happened, and what is the fix?
Java8 · When is parallelStream() a mistake?
- Does a parallel stream preserve order?
- Does going parallel lose encounter order?
- How do you make a parallel stream use a different pool?
- Is parallelStream() asynchronous?
- Two unrelated services in one JVM both call `parallelStream()`. What connects them?
- What breaks when you add .parallel() to working code?
- When would you actually use one?
- Which pool does a parallel stream use?
- Why does reduce need an associative operator?
- Why is that a problem?
- You add `.parallel()` and the results are sometimes wrong, with no exception. Name two causes.
Java8 · Why does a stream with no terminal operation do nothing?
- `list.stream().filter(x).map(y)` with no terminal operation — what runs?
- Can you reuse a stream?
- Does a five-operation chain read the list five times?
- How does findFirst avoid scanning a million elements?
- In a `filter` then `map` then `forEach` chain over four elements, what is printed first after the first `filter` call?
- Is a stream faster than a for loop?
- What is the difference between an intermediate and a terminal operation?
- Which operations break that one-at-a-time flow?
- Why can a `peek` before `count()` never run, and what does that tell you?
- Why is peek a bad place for real work?
Oop · Is Java pass-by-value or pass-by-reference?
- Are arrays special?
- How would you write a method that swaps two values, then?
- In one sentence, why can a method change your object but not replace it?
- Prove it.
- So objects are passed by reference?
- Then why did my list change after I passed it to a method?
- Which single experiment settles "is Java pass-by-reference?" and what does it show?
- Why do String and Integer seem to behave differently?
- You must guarantee a method cannot modify the list you pass it. What do you do?
Oop · What is the contract between hashCode() and equals()?
- `a.hashCode() == b.hashCode()` is true. What, if anything, do you know about `a.equals(b)`?
- A class overrides `hashCode()` but not `equals()`. Can it be used as a `HashMap` key?
- Does equals() have to be symmetric? What about across a subclass?
- I overrode equals() and not hashCode(). What happens?
- Is Objects.hash() the right default?
- Must unequal objects have different hash codes?
- Why is `record` a better key type than a hand-written class with the same fields?
- Why must a key be immutable?
Spring aop · How does Spring AOP work, and what are its limits?
- A method reference `this::doWork` passed to a stream — is the annotation on `doWork` applied?
- How does Spring AOP work?
- How would you prove an aspect is actually applied?
- My @Cacheable method is being called every time. Why?
- Two aspects on one method. Which runs first?
- When does Spring pick CGLIB over a JDK proxy?
- When would you use AspectJ instead?
- Why can't a final method be advised?
- Why does an annotation on a @PostConstruct-called method do nothing?
- Why does injecting the concrete class break once an aspect is added, and why only sometimes?
- Your around-advice measures a duration that is always far shorter than the real call. What would you check first?
Spring core · Why is constructor injection preferred over field injection?
- Do you need @Autowired on the constructor?
- How does field injection let a circular dependency work?
- Is field injection ever acceptable?
- Two beans depend on each other. What happens under each strategy, and which do you want?
- What does field injection actually cost at runtime?
- Why can't a field-injected field be final?
- Why does `final` on an injected field matter for a singleton bean specifically?
- Why does calling a dependency from a constructor throw with field injection but not with constructor injection?
- Why is constructor injection preferred?
- Your constructor has nine parameters. What do you do?
Spring data · How does @Transactional actually work, and when does it silently do nothing?
- A method debits an account then throws a checked exception. What is in the database?
- How does @Transactional work?
- How would you fix a self-invocation problem?
- I annotated a method and it isn't transactional. Why?
- In one sentence, why does a self-invoked `@Transactional` method do nothing?
- Should a transactional method make an HTTP call?
- What does REQUIRESNEW actually do?
- Which exceptions roll back by default?
- Why does @Transactional on a private method not work, but the code still compiles?
- Why is calling a payment gateway inside a transactional method a problem?
Strings · What is the difference between String, StringBuilder and StringBuffer?
- `new StringBuilder("hello").capacity()` — what and why?
- Difference between + and concat on null?
- Does + compile to StringBuilder?
- How do you join a list with commas?
- In one sentence, why is `s += "x"` in a loop quadratic?
- So is "a" + b + c a performance problem?
- StringBuilder or StringBuffer?
- Two threads append to one shared `StringBuffer`. Is the result correct?
- What's the default capacity, and why care?
- Why is String concatenation in a loop slow?
Strings · Why is String immutable, and what is the string pool?
- `"hel" + "lo" == "hello"` is `true`, but with `String p = "hel"; p + "lo" == "hello"` it's `false`. What single word explains the difference?
- Does + still compile to StringBuilder?
- Give me a real reason immutability matters beyond thread safety.
- Is String immutable because the value field is final?
- What does substring() cost?
- What is a String actually made of on Java 21?
- Where does the pool live, and has that changed?
- Why did compact strings ship as a JVM-internal change rather than an API change?
- Why does == sometimes work on strings?
- You reflect into a `String` and overwrite its backing array. `hashCode()` afterwards returns the old value. Why, and why does that matter?
Practice round · Full round replay — @Transactional
Practice round · Full round replay — ArrayList vs LinkedList
Practice round · Full round replay — checked vs unchecked
- Beyond brevity, why use try-with-resources instead of finally?
- Can a finally block swallow an exception?
- int x = 1; try { return x; } finally { x = 2; } — what comes back?
- Should you ever catch Throwable?
- What did Java 8 change about that argument?
- What single fact decides whether an exception is checked?
- Which should you prefer for new code?
- You catch InterruptedException and log it. What did you break?
Practice round · Full round replay — collectors
- How do you get the highest paid person per department?
- How would you compute a count and a total in one pass?
- Is the list inside a groupingBy result safe to mutate?
- What exactly does toMap do on a duplicate key?
- What is a downstream collector, and name three.
- What map type does groupingBy return, and can you rely on its order?
- Why can groupingBy never have either problem?
Practice round · Full round replay — ConcurrentHashMap
- `map.computeIfAbsent(k, x -> new ArrayList<>()).add(item)` — safe?
- Can you use size() to enforce a capacity?
- Do reads take a lock?
- How did this work before Java 8?
- Is `if (!map.containsKey(k)) map.put(k, v)` safe here?
- Where exactly is the lock taken on a write?
- Which compound method for a counter?
- Why does it reject null keys and values?
Practice round · Full round replay — dependency injection
- Boot 2.6 made circular references fail by default. Was that the right call?
- Do you need @Autowired on a constructor?
- I call an injected dependency from my constructor and get a NullPointerException. Why?
- Is field injection ever the right choice?
- Someone adds @Lazy to break the cycle. Good fix?
- What does field injection cost at runtime?
- Why can a constructor-injected field be final but a field-injected one cannot?
- Your constructor has nine parameters. What now?
Practice round · Full round replay — hashCode/equals
- Does javac warn you about that?
- I override equals() and not hashCode(). What do I see at runtime?
- Is it legal for hashCode() to read fewer fields than equals() compares?
- Must two unequal objects have different hash codes?
- So is a hashCode() that returns a constant broken?
- Why is a record a better key than a hand-written class?
- Why must a map key be immutable?
Practice round · Full round replay — HashMap
Practice round · Full round replay — parallel streams
- Does parallel lose encounter order?
- How do you give a parallel stream its own pool?
- What makes a source good or bad for parallelism?
- What silently breaks when you add .parallel() to working code?
- Which pool does it use?
- Why is a slow remote call inside one a problem beyond being slow?
- Why must a reduce operator be associative?
Practice round · Full round replay — pass-by-value
Practice round · Full round replay — Spring AOP
- Does a method reference like this::doWork go through the proxy?
- How would you prove in a test that an aspect is applied?
- My @Cacheable method runs every time. Where do you look?
- When is AspectJ the right answer instead?
- Which proxy does Spring create, and when?
- Why can a final method not be advised?
- Why does an annotation on a method called from @PostConstruct do nothing?
- Why does injecting the concrete class sometimes fail once an aspect is added?
Practice round · Full round replay — stream laziness
Practice round · Full round replay — String immutability and the pool
- Does adding final to a local variable change the result of a == comparison?
- Give me a reason immutability matters that isn't thread safety.
- Is it immutable because the value field is final?
- Then why does == sometimes work on strings?
- What does substring() cost, and has that changed?
- What is a String made of on Java 21?
- Where does the pool live?
Practice round · Full round replay — String vs StringBuilder
Practice round · Full round replay — the memory model
- A field is written before thread.start() and read inside the thread. Does it need volatile?
- A producer writes five plain fields then counts down a latch. Are they visible after await()?
- Does it mean A executes before B in time?
- How do you publish a config object safely with no lock on the read path?
- How would you prove the code has no visibility bug?
- The field is volatile and the object is immutable, but describe() reads it twice. Safe?
- What does final guarantee, and when does it not?
- What happens when there is no edge between a write and a read?
Practice round · Full round replay — volatile and synchronized
GCC / captive centres · 1-2 years
GCC / captive centres · 3-4 years
- How do you make an API idempotent?
- How do you test code that calls an external service?
- How does @Transactional work, and when does it silently not apply?
- How would you handle a partial failure mid-transaction?
- Is HashMap thread-safe? What breaks specifically?
- What is the difference between a stream and a parallel stream?
GCC / captive centres · 5-6 years
- Design a payment reconciliation system. What is your source of truth?
- How do you achieve exactly-once processing, or can you?
- How do you diagnose a memory leak in production?
- How do you migrate a schema with zero downtime?
- How do you size a thread pool, and how would you know it is wrong?
- What are virtual threads, and would they help this service?
- What would you monitor for this service, and what would page you?
Product-based · 1-2 years
Product-based · 3-4 years
Product-based · 5-6 years
- Design a URL shortener for 100 million writes a day.
- How do you choose between strong and eventual consistency here?
- How do you find and fix a memory leak in a live service?
- How do you size and shut down a thread pool correctly?
- How would you diagnose rising p99 latency with normal CPU?
- Tell me about a time you disagreed with a technical decision.
Service-based · 1-2 years
Service-based · 3-4 years
Service-based · 5-6 years
- How do you handle a slow SQL query reported in production?
- How do you review a junior developer's pull request?
- How do you size a thread pool for an I/O-bound service?
- How does @Transactional actually work, and when does it silently not?
- How would you debug a memory leak in production?
- Is HashMap thread-safe? How would you make it safe?
- What would you change about your current project's design?
Java 10 · Local-variable type inference (var)
Java 11 · HTTP Client (standard)
Java 11 · Launch single-file source-code programs
Java 11 · Remove the Java EE and CORBA modules
Java 11 · String convenience methods
Java 12 · Switch expressions (preview)
Java 13 · Text blocks (preview)
Java 15 · Helpful NullPointerExceptions
Java 15 · Text blocks
Java 16 · Pattern matching for instanceof
Java 16 · Records
Java 17 · Deprecate the Security Manager for removal
Java 17 · Sealed classes
- How do sealed types, records and pattern matching work together?
- Why must a sealed type's permitted subclasses be in the same module or package?
- You are modelling the result of an operation as either a success with a value or one of three specific failures, and every call site must handle all four. How do you model it so a missed case cannot compile?
Java 17 · Strongly encapsulate JDK internals
Java 21 · Generational ZGC
Java 21 · Pattern matching for switch
- A payment handler branches on eight event types with instanceof and casts. A ninth type was added last month and one branch was missed, which reached production. How do you make that class of bug impossible?
- What does a guarded pattern let you express?
- What is exhaustiveness, and when does the compiler enforce it?
Java 21 · Record patterns
Java 21 · Sequenced collections
- Code uses LinkedList throughout because the original author wanted getFirst() and getLast(), and profiling now shows heavy indexed access on those lists. What do you change?
- Did addFirst on an ArrayList get any faster?
- Is reversed() a copy or a view?
- What did SequencedCollection add, and what problem did it solve?
Java 21 · String templates
Java 21 · Virtual threads
- A batch job spends its time on CPU-bound image transformation and currently uses a pool sized to the core count. Would you move it to virtual threads?
- A service handles 5,000 concurrent requests, each spending 200ms waiting on two database calls. It runs a 200-thread pool and queues under load. Do virtual threads help, and what do you change?
- Why do virtual threads not speed up CPU-bound work?
Java 22 · Foreign Function and Memory API
Java 22 · Launch multi-file source-code programs
Java 22 · Unnamed variables and patterns
Java 23 · Markdown documentation comments
Java 24 · Permanently disable the Security Manager
Java 24 · Stream gatherers
Java 24 · Synchronize virtual threads without pinning
- A service on JDK 21 moved to virtual threads and got no throughput improvement. Profiling shows carrier threads blocked inside a third-party client that synchronizes around its socket calls. What is happening, and what are your options?
- What was thread pinning, and which release fixed it?
- Why did ReentrantLock avoid the problem when synchronized did not?
Java 25 · Compact object headers
Java 25 · Compact source files and instance main methods
- Can a Java program run without a class declaration?
- Does main still have to be static?
- Why did it take until Java 25 to simplify Hello World?
- You are writing training material for developers new to Java, and your organisation is on JDK 17 in production but can use 25 for learning. Do you teach the compact form or the classic form first?
Java 25 · Flexible constructor bodies
- A subclass constructor must reject a negative amount before the superclass constructor runs, because the superclass registers the object in a static collection. How would you have solved this before 25, and now?
- How did you validate constructor arguments before Java 25?
- Why could nothing come before super() in a constructor?
Java 25 · Module import declarations
Java 25 · Scoped values
- A request-scoped tenant id needs to reach code six layers deep. The service is moving to virtual threads and may create hundreds of thousands of them. ThreadLocal, a parameter, or a scoped value?
- What problem do scoped values solve that ThreadLocal does not?
- Why do virtual threads make ThreadLocal more of a problem?
Java 25 · Structured concurrency
- A request fans out to three services and needs all three to succeed. Today one failure leaves the other two calls running and the request hanging until timeout. How do you fix it, and what would structured concurrency change?
- What problem does structured concurrency solve that ExecutorService does not?
- Why has structured concurrency been in preview for so many releases?