Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: 5–8 Years

Revise the 2–5 Years Tier

  • Revise: Core Java & Java 8+ (2–5 Years Tier)
  • Revise: Multithreading & Concurrency (2–5 Years Tier)
  • Revise: Spring Framework, Spring Boot & Security (2–5 Years Tier)
  • Revise: Kafka, Git/Maven/Gradle, Deployment & Testing (2–5 Years Tier)

Advanced Core Java

  • Advanced OOP & Design Scenarios — Interview Questions
  • Advanced Concurrency, Collections & Memory — Interview Questions
  • Modern Java Language Features & Annotations — Interview Questions
  • Class Loading, Reflection, Serialization & Idioms — Interview Questions

Java Design Patterns in Depth

  • Design Patterns Overview & Singleton — Interview Questions
  • Factory & Abstract Factory Patterns — Interview Questions
  • Builder & Prototype Patterns — Interview Questions
  • Adapter & Bridge Patterns — Interview Questions
  • Composite & Decorator Patterns — Interview Questions
  • Facade & Proxy Patterns — Interview Questions
  • Chain of Responsibility & Observer Patterns — Interview Questions
  • Strategy & Template Method Patterns — Interview Questions
  • Command Pattern — Interview Questions

Advanced Spring Boot

  • Logging, Configuration & Actuator (Advanced) — Interview Questions
  • Transactions, Multiple Datasources & Query Tuning — Interview Questions
  • Validation & REST API Design (Advanced) — Interview Questions
  • Reactive, Async & Scheduling in Spring Boot — Interview Questions
  • Deployment, High Availability, Scaling & Caching — Interview Questions
  • Custom Starters, DI, Testing & DevTools — Interview Questions

Spring Security for APIs

  • Securing REST APIs End to End — Interview Questions

Microservices at Scale

  • Monolith Migration, Communication & Spring Cloud — Interview Questions
  • Data Consistency, Sagas & Kafka Messaging — Interview Questions
  • Tracing, Discovery, Load Balancing, Service Mesh & Resilience — Interview Questions
  • Deployment, Scaling & Security for Microservices — Interview Questions

Microservice Design Patterns

  • API Gateway, Circuit Breaker & Retry Patterns — Interview Questions
  • Service Discovery & Database per Service Patterns — Interview Questions
  • Saga, Choreography & Orchestration Patterns — Interview Questions
  • Bulkhead & Strangler Fig Patterns — Interview Questions
Chaturmind
← Java Interview Prep: 5–8 Years

Revise the 2–5 Years Tier

  • Revise: Core Java & Java 8+ (2–5 Years Tier)
  • Revise: Multithreading & Concurrency (2–5 Years Tier)
  • Revise: Spring Framework, Spring Boot & Security (2–5 Years Tier)
  • Revise: Kafka, Git/Maven/Gradle, Deployment & Testing (2–5 Years Tier)

Advanced Core Java

  • Advanced OOP & Design Scenarios — Interview Questions
  • Advanced Concurrency, Collections & Memory — Interview Questions
  • Modern Java Language Features & Annotations — Interview Questions
  • Class Loading, Reflection, Serialization & Idioms — Interview Questions

Java Design Patterns in Depth

  • Design Patterns Overview & Singleton — Interview Questions
  • Factory & Abstract Factory Patterns — Interview Questions
  • Builder & Prototype Patterns — Interview Questions
  • Adapter & Bridge Patterns — Interview Questions
  • Composite & Decorator Patterns — Interview Questions
  • Facade & Proxy Patterns — Interview Questions
  • Chain of Responsibility & Observer Patterns — Interview Questions
  • Strategy & Template Method Patterns — Interview Questions
  • Command Pattern — Interview Questions

Advanced Spring Boot

  • Logging, Configuration & Actuator (Advanced) — Interview Questions
  • Transactions, Multiple Datasources & Query Tuning — Interview Questions
  • Validation & REST API Design (Advanced) — Interview Questions
  • Reactive, Async & Scheduling in Spring Boot — Interview Questions
  • Deployment, High Availability, Scaling & Caching — Interview Questions
  • Custom Starters, DI, Testing & DevTools — Interview Questions

Spring Security for APIs

  • Securing REST APIs End to End — Interview Questions

Microservices at Scale

  • Monolith Migration, Communication & Spring Cloud — Interview Questions
  • Data Consistency, Sagas & Kafka Messaging — Interview Questions
  • Tracing, Discovery, Load Balancing, Service Mesh & Resilience — Interview Questions
  • Deployment, Scaling & Security for Microservices — Interview Questions

Microservice Design Patterns

  • API Gateway, Circuit Breaker & Retry Patterns — Interview Questions
  • Service Discovery & Database per Service Patterns — Interview Questions
  • Saga, Choreography & Orchestration Patterns — Interview Questions
  • Bulkhead & Strangler Fig Patterns — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 5–8 YearsRevise the 2–5 Years Tier
✓ FreeAdvanced· 63 min read

Revise: Kafka, Git/Maven/Gradle, Deployment & Testing (2–5 Years Tier)

Every 2–5-year question on Kafka, Git, Maven and Gradle, CI/CD and deployment, JUnit and Mockito — one-line answers with links to the full answers.

Published September 25, 2026


How to use this revision

This page condenses every question from the 2 to 5 Years course in these areas into a single line: the question, linked to its full answer, and the one-sentence answer you should be able to give instantly. Read down the list and answer each question aloud before reading the line. Wherever you hesitate, follow the link and revise the full answer — interviewers at your level expect these basics to be fluent, and they often open with them before going deeper.

Apache Kafka

Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions — open the lesson

  • What is Apache Kafka? — Kafka is a distributed, partitioned, replicated commit log, used as an event-streaming platform. Producers append records to topics.
  • What are Kafka's common use cases? — Event-driven microservices: order placed → inventory, billing, notifications; Change data capture: database changes streamed through Debezium; Log and metrics aggregation, and activity tracking (clicks, views); Real-time stream processing: fraud detection, alerting, live…
  • How does Kafka differ from traditional messaging systems? — Compared side by side in the full answer (table) — know each row.
  • What components make up the Kafka architecture? — Brokers: servers that store partitions and serve clients. A cluster is a set of brokers; Topics, split into partitions, which are replicated across brokers. Each partition has one leader and some followers; Producers write, and consumers (grouped into consumer groups) read;…
  • What is a Kafka topic? — A topic is a named, append-only stream of records for one kind of event (orders.placed). It's split into partitions for parallelism, and each partition is an ordered log in which each record has an offset.
  • How do you create a topic? — Use the CLI, the Admin API, or declarative infrastructure-as-code — kafka-topics.sh --bootstrap-server broker:9092 --create --topic orders.placed \
  • How are topics partitioned, and why does it matter? — A topic's partitions are spread across brokers. A producer chooses a partition by: hashing the record key, so the same key always goes to the same partition; sticky batching, when there's no key; a custom partitioner.
  • What happens when a topic is replicated? — Each partition has replication-factor copies on different brokers: The leader handles all writes, and by default all reads; Followers fetch from the leader to stay in sync; Replicas that are caught up form the ISR (in-sync replica set); If the leader fails, a new leader is…
  • What was ZooKeeper's role in Kafka? — In older Kafka (before KRaft), ZooKeeper stored the cluster metadata: broker registration and liveness; topic and partition configuration; ACLs and quotas.
  • Why was ZooKeeper critical for Kafka (and why did Kafka remove it)? — In ZooKeeper-based clusters, it was the source of truth for metadata, and the anchor for controller election. Without it, the cluster couldn't change leadership or configuration safely.
  • What would happen if ZooKeeper failed? — Existing leaders keep serving produce and consume requests for their partitions, so the data path mostly continues; The control plane freezes:; Long outages leave the cluster increasingly fragile.
  • How does Kafka handle ZooKeeper outages, and what's the modern answer? — In older clusters: brokers keep their cached metadata and continue serving, while metadata operations are blocked until a ZooKeeper quorum returns.

Kafka Producers, Consumers, Reliability & Streams — Interview Questions — open the lesson

  • What are Kafka producers and consumers? — Producers publish records (key, value, headers, timestamp) to topics. Consumers pull records from partitions, and track their position with offsets.
  • How do producers send data to Kafka? — The producer serialises the key and value; It picks a partition: by key hash (same key → same partition, which preserves per-key order), or with the sticky partitioner when there's no key; It batches records per partition in memory (batch.size, linger.ms), and optionally…
  • What strategies do consumers use to read data? — Subscribe to topics as part of a group (automatic partition assignment and rebalancing), or assign specific partitions manually; Where to start with no committed offset: auto.offset.reset = earliest or latest; How to commit offsets:; Batch vs per-record processing, and…
  • How do consumer groups help Kafka scale? — Within a group, each partition is consumed by exactly one member. Adding consumers spreads the partitions across more instances (horizontal scaling), up to one consumer per partition.
  • How does Kafka achieve fault tolerance? — Replication: each partition has copies on several brokers, spread across racks or AZs; Leader election from the ISR when a broker fails; Durable, append-only logs on disk; Controller quorum (KRaft), for metadata high availability; …
  • What is the role of replication in Kafka? — Replication keeps redundant copies of each partition, so a broker failure causes no data loss and only a brief interruption for leader election.
  • How does Kafka make sure data isn't lost? — Only when the whole chain is configured for it.
  • What is the significance of the producer's acks setting? — It defines when a write counts as successful: acks=0: fire-and-forget. Fastest, but data can be lost silently; acks=1: the leader has written it. Data is lost if the leader fails before the followers replicate it; acks=all (-1): all in-sync replicas have it. That's…
  • What is Kafka Streams, and what is it used for? — Kafka Streams is a Java library for building stream-processing applications that read from Kafka topics, transform, join, aggregate and window the data, and write the results back to Kafka. It runs inside your own application, with no separate cluster. Use cases: real-time…
  • What differentiates Kafka Streams from other stream-processing frameworks? — It's a library, not a cluster. You deploy it like any Java app (in containers, scaled by running more instances), unlike Flink or Spark, which need their own cluster managers; It's Kafka-native. It uses Kafka for input and output, for state backup (changelog topics), for…
  • How does Kafka Streams handle state? — Stateful operations (aggregations, joins, windows) keep their state in local state stores: RocksDB by default, or in memory.
  • What are the challenges of using Kafka Streams? — State restoration time: large stores can take minutes to rebuild after a rebalance. Mitigate with standby replicas and warm-up; Rebalances pause processing; Repartition topics created implicitly by groupBy/selectKey add latency and storage; Disk sizing for RocksDB, and…

Kafka Security, Connect & Core Scenarios — Interview Questions — open the lesson

  • How do you secure a Kafka cluster? — Defence in layers: Encryption in transit: TLS on client and inter-broker listeners; Authentication: SASL (SCRAM-SHA-512, OAUTHBEARER/OIDC, or Kerberos/GSSAPI), or mTLS client certificates; Authorisation: ACLs per principal (topic read/write, consumer-group access, cluster…
  • What security mechanisms does Kafka provide? — Compared side by side in the full answer (table) — know each row.
  • How would you implement encryption in Kafka? — In transit:; At rest: encrypted disks or volumes; End to end: encrypt sensitive payload fields in the producer (for example, envelope encryption with a KMS), so even broker admins can't read them.
  • What are the best practices for securing Kafka at scale? — One principal per application, with least-privilege ACLs managed as code (Terraform or GitOps); Prefixed ACLs per team namespace (orders.*); Short-lived credentials: OAuth or SCRAM with rotation; Automated certificate rotation.; …
  • Discuss Kafka Connect. — Kafka Connect is Kafka's integration framework for moving data into Kafka (source connectors: databases through Debezium CDC, files, SaaS APIs) and out of Kafka (sink connectors: Elasticsearch, S3, data warehouses, JDBC), without writing custom producer or consumer code.
  • What is Kafka Connect, and why is it useful? — It saves you from writing and operating fragile, bespoke integration code. You get reusable, battle-tested connectors, exactly-once support for sources that allow it (and many sinks), automatic offset management, distributed scaling, dead-letter queues for bad records, and…
  • How do you scale Kafka Connect? — Run Connect in distributed mode, as a cluster of workers sharing a group ID. Connectors are split into tasks (tasks.max), and the tasks are balanced across the workers; Scale by adding workers and raising tasks.max, up to what the connector supports. For sinks, that's…
  • What problems commonly occur with Kafka Connect? — Misconfiguration: wrong converters (JSON with schemas vs Avro), missing permissions, bad SMTs; Poison records: configure errors.tolerance=all with a dead-letter queue topic, and log the context; Schema drift between the source and the sink; Rebalances when workers or…
  • How do you make sure messages with the same key are processed in the order they were sent? — Produce with the key (for example orderId), so all of a key's messages land in the same partition, where order is preserved; Keep producer ordering safe with idempotence enabled (the default), which preserves order even with retries and several in-flight requests; On the…
  • Consumers are lagging behind the producers. What do you do? — Measure. Is the lag growing on all partitions (capacity) or on a few (hot partitions, or a stuck consumer)? Is processing slow (database or downstream calls) or is fetching slow?; Scale consumers, up to the partition count. If the partition count is the limit, add partitions…
  • Your application needs exactly-once processing. How do you configure Kafka? — Kafka's exactly-once covers read → process → write within Kafka: Producer: enable.idempotence=true, plus a transactional.id; Consume, process and produce inside a transaction, sending the consumed offsets within the same transaction (sendOffsetsToTransaction);…
  • How do you evolve a topic's message schema without breaking existing consumers? — Use a schema format with evolution rules (Avro, Protobuf or JSON Schema), and a Schema Registry (Confluent or Apicurio); Set a compatibility mode per subject, typically BACKWARD (new consumers can read old data), or FULL; Make only compatible changes: add optional fields with…

Kafka Production Scenarios — Interview Questions — open the lesson

  • How do you configure Kafka for high availability and fault tolerance? — Compared side by side in the full answer (table) — know each row.
  • How do you handle duplicates caused by consumer rebalances or producer retries? — Producer retries: keep idempotence enabled (the default since 3.0), so broker-side sequence numbers drop the duplicates; Consumer rebalances and crashes: with at-least-once delivery, records processed but not yet committed are redelivered. You can't avoid that, so:;…
  • Your messages are bigger than the default ~1 MB limit, and they're causing problems. What do you do? — Prefer not to put large payloads into Kafka: Claim-check pattern: store the payload in object storage (S3), and send a small message with a reference (the key or URL, plus a checksum); Compress (zstd), and trim the payload; Split into chunks, with a correlation ID and…
  • A consumer group is falling far behind. How do you handle it? — Diagnose with the lag per partition (kafka-consumer-groups.sh --describe, Burrow, or Prometheus exporters); If processing is slow: optimise the handlers, batch the downstream writes, and parallelise per key; If the consumer count < the partition count: add consumers; If…
  • A broker fails unexpectedly. How do you keep the cluster available? — It's mostly automatic, if the cluster was configured correctly beforehand: The controller elects new leaders from the ISR for the partitions the failed broker led. Clients refresh their metadata, and reconnect to the new leaders; With replication factor 3 /…
  • How do you keep data consistent when several consumers read the same topic? — It depends on what "several consumers" means: The same consumer group: each partition goes to exactly one member, so a record is processed by one consumer. Per-key ordering holds if keys map to partitions. Commit after processing, and make handlers idempotent, for crash…
  • Which metrics matter for Kafka performance, and how do you troubleshoot a throughput drop? — Brokers:; Producers: record send rate, error and retry rates, batch size, request-latency; Consumers: lag, records consumed per second, rebalance rate, commit latency; Hosts: CPU, disk I/O and latency, network, GC.
  • What happens when a partition leader fails, and how does leader election work? — The controller detects the failure (broker heartbeat or session loss); It chooses a new leader from the partition's ISR, preferring the first live in-sync replica in the assignment order; It updates the metadata. In KRaft, that's a record in the replicated metadata log;…
  • Why do consumer-group rebalances sometimes take long, and how do you shorten them? — Classic ("eager") rebalances are stop-the-world. Every member revokes all its partitions, commits, waits for the slowest member to rejoin, then gets a new assignment.
  • Can you lose data in Kafka even with replication? How? — Yes: acks=0 or acks=1: the leader acknowledges, then dies before followers replicate; min.insync.replicas=1: acks=all degenerates to "leader only" when followers fall behind; Unclean leader election: an out-of-sync replica becomes leader, and truncates the…
  • When would you use a compacted topic instead of a regular one, and what are the trade-offs? — Use log compaction (cleanup.policy=compact) when consumers need the latest state per key, not the full history: entity snapshots (customer profile, product price); Kafka Streams changelogs and KTables; CDC tables; configuration topics (Kafka Connect's own internal topics).
  • Kafka guarantees ordering, but when can that guarantee break? — Ordering is guaranteed only within a single partition, for a single producer's successful writes. It can break when: Related messages go to different partitions: no key, the wrong key, or different producers choosing different keys; The partition count changes: `hash(key) %…

Git, Maven & Gradle (Level II)

Git Workflows, Rebase & Conflict Handling — Interview Questions — open the lesson

  • What's your strategy for managing branches on a collaborative project? — Keep main always releasable, and protected (required reviews, required CI checks, no direct pushes). Work on short-lived feature branches (days, not weeks), cut from the latest main.
  • A merge conflict hits a critical piece of code just before deployment. What do you do? — Don't rush it. Pause the release. A wrong resolution in critical code is worse than a delay; Understand both changes. Read both sides and the commits' intent (git log -p), and bring in the authors; Resolve it deliberately, then run the full test suite (and targeted manual…
  • How does git rebase work, and when should you use it instead of merge? — git rebase main takes the commits that are on your branch but not on main, temporarily removes them, moves your branch to the tip of main, and replays each commit on top, creating new commits with new hashes.
  • How do you manage merge conflicts in Git? — git status lists the conflicted files; Open each file, and resolve the <<<<<<< / ======= / >>>>>>> regions by intent, not by picking a side blindly; Use git mergetool or your IDE's three-way merge view, which shows the base, ours and theirs; Build and test.; …
  • Explain the rebase process, and its advantages over merging. — Rebase rewrites your branch's commits onto a new base. Its advantages: a linear, readable history, no noisy "Merge main into feature" commits, easier git bisect and git log, and the chance to tidy commits before review.
  • How do you clone a repository from GitHub? — git clone <url>. Use SSH (git@github.com:org/repo.git) for key-based authentication, or HTTPS with a token or credential manager. Useful options: --branch <name> to check out a specific branch; --depth 1 (a shallow clone for CI); --filter=blob:none (a partial clone…
  • What does git pull do? — git pull = git fetch (download new commits into origin/<branch>) plus integrating them into your current branch.
  • Scenario: you need changes a teammate is still working on in another branch. How do you integrate them? — The options, in order of preference: Wait for their PR to merge to main, then rebase onto main. This keeps both histories clean; If you truly can't wait, base your work on their branch: git fetch origin && git rebase origin/their-feature (or `git merge…
  • Scenario: after several commits, you find a mistake in an earlier one. How do you correct it? — Not yet pushed (a private branch): fix it with an interactive rebase. Either mark the commit edit and amend it, or better, commit the fix as a fixup and let Git squash it in.
  • How do you review a large number of pull requests effectively? — Automate the mechanical checks (formatting, linting, tests, coverage, security and dependency scanning), so reviews focus on design and correctness; Keep PRs small, with clear descriptions: why, what changed, how it was tested; Prioritise by risk and urgency. Use CODEOWNERS…

Git Recovery, Hooks, Tags & Collaboration — Interview Questions — open the lesson

  • You accidentally committed sensitive information, such as a password. What do you do? — In this order: Rotate or revoke the secret immediately. Assume it's compromised the moment it was pushed. Bots scan public repositories within minutes, and forks, clones and CI caches may already hold it; Remove it from the code going forward: move it to environment variables…
  • How can Git hooks improve a team's workflow? — Hooks are scripts that Git runs at points in its workflow: Client-side: pre-commit (format, lint, scan for secrets), commit-msg (enforce message conventions), pre-push (run fast tests); Server-side: pre-receive, update (reject pushes that break policy).
  • You've changed a file a lot, and want an earlier version of it without losing your current work. How? — View or extract the old version, without touching your working copy — git show <commit>:src/main/java/com/shop/Pricing.java > /tmp/Pricing.old.java # a copy to compare git…
  • How can you track changes made by others in a shared repository? — Fetch first, then compare your branch with the remote — git fetch --all --prune git log --oneline HEAD..origin/main # commits on the remote that you…
  • Describe a complicated multi-file merge conflict you resolved. — *"Two teams refactored the pricing module in parallel. One renamed classes and moved packages, while the other changed the discount logic, which produced conflicts in 14 files.
  • How do you create and manage tags, and when do you use them? — Tags mark release points. Use annotated tags for releases: they record the tagger, date and message, and can be signed.
  • A teammate pushes a commit that breaks the build. What do you do? — Restore green quickly. If the fix isn't obvious within minutes, git revert the offending commit on main (never force-push main); Identify the cause from the CI logs, or with git bisect, if it isn't clear which commit did it; Tell the author, without blame, and let…
  • What is a "detached HEAD", and how does it happen? — HEAD normally points to a branch, which points to a commit. In a detached HEAD state, HEAD points directly to a commit.
  • How can Git be used together with feature toggles? — Feature toggles (flags) exist precisely so you don't need long-lived feature branches. You merge incomplete features into main continuously, hidden behind a runtime flag, and release them by switching the flag on, which is independent of deploying.
  • You need to share changes from a feature branch with another developer without merging. How? — Push the branch, and have them check it out — git push -u origin feature/export-v2 git fetch origin

Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions — open the lesson

  • Describe a complex Maven build you've configured. Which plugins and configuration mattered? — maven-compiler-plugin: release 21, -parameters, annotation processors (MapStruct, Lombok) in a defined order; maven-surefire-plugin runs the unit tests, and maven-failsafe-plugin runs *IT integration tests in integration-test/verify, using Testcontainers;…
  • How would you optimise a Maven build for a large multi-module project? — Parallel reactor builds: -T 1C; Build only what changed: -pl changed-module -am (plus the modules it depends on), or -amd (plus the modules depending on it); The Maven Build Cache Extension, for incremental builds with local or remote caching; Keep modules cohesive, so…
  • How does Maven dependency resolution work? Describe a conflict you troubleshot. — Maven builds the dependency graph (direct plus transitive dependencies), then mediates versions when the same artifact appears more than once: Nearest definition wins: the version closest to your POM in the tree; At equal depth, the first declaration wins.;…
  • What is the purpose of pom.xml? — It's the project's build model: coordinates (groupId:artifactId:version) and packaging; parent and modules; dependencies and dependencyManagement; build plugins and pluginManagement; …
  • Explain the Maven lifecycles and their phases. — There are three lifecycles: clean: pre-clean, clean, post-clean; default: the build itself: validate, compile, test, package, integration-test, verify, install, deploy, and more; site: documentation.
  • How do you manage a multi-module Maven project and its dependencies? — A parent (aggregator) POM (<packaging>pom</packaging>) lists the <modules>, and centralises:; Modules declare the dependencies they use, without versions; Inter-module dependencies use ${project.version}; Import BOMs (Spring Boot, Testcontainers) with…
  • How would you speed up Maven builds for large projects? — Measure first (see "build time increasing", in the next lesson), then: -T 1C parallel builds; -o offline mode, when the cache is warm; The build cache extension; Selective builds (-pl/-am); …
  • How do starters simplify Maven configuration? — A Spring Boot starter is a single dependency that brings a curated, compatible set of libraries for one capability.
  • Scenario: migrate a legacy project to Maven. How do you ensure a smooth transition? — Inventory the current build: Ant targets, lib/*.jar files, code generation, packaging, deployment steps; Map the JARs to Maven coordinates. Identify each JAR by checksum and search Maven Central. Upload internal or unknown JARs to the company repository manager (not…
  • How do you handle version conflicts between dependencies in Maven? — Find them with mvn dependency:tree -Dverbose, and the Enforcer's dependencyConvergence rule; Pin the version you want in <dependencyManagement>, preferably through the library's BOM (the Jackson, Netty or AWS SDK BOMs), so related modules stay aligned; Exclude unwanted…

Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions — open the lesson

  • How can Maven profiles be used to manage different environments? — A profile changes the build: extra dependencies, plugin configuration, properties or modules. It's activated with -Pname, or automatically by JDK version, OS, a property or a missing file. Legitimate uses: optional build features (-Pnative, -Pintegration-tests,…
  • Describe implementing a custom Maven plugin. What was the challenge? — *"We needed every service JAR to include a release-manifest.json with the git commit, dependency licences and API version, which no existing plugin produced in our format.
  • How can Maven generate project documentation automatically? — The site lifecycle (mvn site, with maven-site-plugin) produces a website from reporting plugins: Javadoc, Surefire and Failsafe reports, JaCoCo coverage, dependency and licence reports, SpotBugs, Checkstyle; API docs: maven-javadoc-plugin (a -javadoc.jar for published…
  • Scenario: the build fails because an external dependency is unavailable. What do you do? — Diagnose: is it the network, a proxy, credentials, a removed artifact, or an outage at the upstream repository? Run with -e/-X, check settings.xml mirrors, and check whether the version really exists; Short term: use the company repository manager (Nexus or Artifactory)…
  • How would you reduce the size of a Maven project and its artifacts? — Remove unused dependencies: mvn dependency:analyze reports "declared but unused" and "used but undeclared"; Exclude heavy transitive dependencies you don't need, such as an unused servlet container or duplicate logging bindings; Scope correctly: provided, test and…
  • What is settings.xml for? — It configures Maven itself, on a given machine or user, rather than a project. User settings live in ~/.m2/settings.xml, and global ones in ${maven.home}/conf/settings.xml. It holds: repository credentials (<servers>, referenced by the ID of the repository or…
  • Scenario: Maven build times keep increasing. How do you diagnose it? — Measure per module and per plugin. Maven 3.9 prints each module's time. -Dmaven.ext.class.path profilers or the Gradle Enterprise / Develocity build scans for Maven show where the time goes; Check dependency resolution: repository timeouts, SNAPSHOT update checks…
  • How do you enforce coding standards and static analysis in a Maven project? — Bind quality plugins to the lifecycle, and fail the build on violations: Formatting: Spotless (auto-formats with spotless:apply, verifies with spotless:check); Style: Checkstyle; Bug patterns: SpotBugs (the maintained successor of the dead FindBugs), plus the FindSecBugs…
  • How do you use dependency:tree, and why is it useful? — mvn dependency:tree prints the resolved dependency graph: every direct and transitive dependency, its version and scope. It's useful for: explaining where a library comes from (-Dincludes=groupId:artifactId); spotting conflicts (-Dverbose shows omitted duplicates, and…
  • Scenario: you need a specific version of a dependency that isn't compatible with the rest of your project. What do you do? — First check whether you truly need it: a newer compatible release, a patch backport or an alternative library may exist. If you must have two incompatible versions: Shade and relocate the dependency in a small wrapper module, with maven-shade-plugin <relocations>. The…

Gradle Fundamentals, Migration & Dependencies — Interview Questions — open the lesson

  • What's the difference between Maven and Gradle? — Compared side by side in the full answer (table) — know each row.
  • What challenges come with migrating from Maven to Gradle, and how do you handle them? — Bootstrap with gradle init, which converts a POM into a starting build (review the result, don't trust it blindly); Recreate the dependency management: the BOMs become platform(...), versions go into a version catalog (gradle/libs.versions.toml), and the scopes map to…
  • How do you manage library dependencies in a Gradle project? — Declare them in dependencies {} with the right configuration, keep their versions in a version catalog, and use platforms (BOMs) to align families of libraries.
  • Scenario: you need a multi-project Gradle build. What do you take into account? — settings.gradle.kts declares the modules (include("api", "domain", "persistence", "app")), and dependency resolution management (repositories, version catalogs); Put shared build logic in convention plugins (build-logic/ as an included build, or buildSrc), such as…
  • How does Gradle's incremental build work, and what are its advantages? — Every task declares its inputs (source files, properties, classpath) and outputs (directories, files). Gradle fingerprints them.
  • Describe troubleshooting a complex Gradle build script. — *"After an upgrade, the build failed with a NoSuchMethodError from a Jackson class, but only in CI. ./gradlew dependencyInsight --dependency jackson-databind --configuration runtimeClasspath showed that a plugin's transitive dependency upgraded Jackson beyond what our…
  • How do you write a custom Gradle task, and what are some use cases? — Register a task lazily with tasks.register. For anything non-trivial, write a task class with typed, annotated inputs and outputs, so it's cacheable and incremental.
  • Scenario: a Gradle build fails because of a version conflict. How do you resolve it? — Find it: ./gradlew dependencyInsight --dependency <lib> --configuration runtimeClasspath explains which version was chosen and why; Fix it, preferring the least forceful option:; Prevent recurrence: dependency locking, failOnVersionConflict() for critical groups, and…
  • How do you manage environment-specific configuration in a Gradle project? — Keep the artifact environment-neutral, and supply environment configuration at runtime: Spring profiles, environment variables, a config server.
  • What's the significance of build.gradle(.kts), and how is it structured? — It's the build script for a project. It configures that project's plugins, dependencies and tasks. A typical structure — plugins {

Gradle Performance, Plugins, Testing & Publishing — Interview Questions — open the lesson

  • Scenario: you need to integrate a third-party library into a Gradle project. What steps do you follow? — Vet the library: licence, maintenance activity, known vulnerabilities, and transitive footprint; Add it to the version catalog, and reference it with the right configuration (implementation, api, runtimeOnly); Make sure the repository is configured (Maven Central or the…
  • How does Gradle handle transitive dependencies, and how can you customise that behaviour? — Gradle resolves the full graph, and when several versions of a module appear, it chooses the highest version by default (unlike Maven's nearest-wins). Gradle Module Metadata adds variants and capabilities, so the right flavour of a dependency is chosen. You can customise this…
  • Scenario: you want to improve Gradle build performance. What do you do? — Measure first with a build scan (--scan) or --profile, then: Enable the build cache (org.gradle.caching=true), local and remote (shared by CI and developers); Enable the configuration cache (org.gradle.configuration-cache=true); Use parallel execution…
  • How do you implement unit tests in a Gradle project? — Put the tests in src/test/java, add JUnit 5, and tell Gradle to use the JUnit Platform — dependencies { testImplementation(platform("org.junit:junit-bom:5.11.0"))
  • How do you use Gradle's build cache, and what are the benefits? — Enable it with org.gradle.caching=true. Cacheable tasks (compilation, tests, code generation) store their outputs keyed by a hash of their inputs.
  • Scenario: configure a Gradle project to publish artifacts to a remote repository. — Apply maven-publish, define a publication (the component, plus the sources and Javadoc JARs), and a repository, with credentials from the environment.
  • How do you automate code-quality checks in a Gradle build? — Apply the quality plugins (Spotless, Checkstyle, PMD, SpotBugs, JaCoCo with coverage verification, Error Prone, and OWASP Dependency-Check), preferably in a convention plugin, so every module gets them.
  • Scenario: many modules must all use the same version of a dependency. How do you manage that? — Centralise the version, not the dependency itself: A version catalog (libs.versions.toml), so every module references libs.jackson.databind with one version; A platform, either an imported BOM or your own java-platform project with constraints, to align families of…
  • How do you create a Gradle plugin, and what is it used for? — Implement Plugin<Project>, and in apply(), apply other plugins, register tasks and extensions (the configurable DSL).
  • What does the Gradle Wrapper give you over a global Gradle installation? — The Wrapper (gradlew plus gradle/wrapper/gradle-wrapper.properties) pins the Gradle version per project, and downloads it automatically.

Deployment & CI/CD

Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions — open the lesson

  • How do you configure session clustering in Spring Boot? — Use Spring Session with a shared store, usually Redis. Add spring-session-data-redis plus spring-boot-starter-data-redis, and point it at Redis.
  • Users lose their sessions when the app runs on several servers. What's your strategy? — The session lives in one instance's memory, so when the load balancer sends the next request to another instance, or the instance restarts, the session is gone. The options: Externalise the sessions with Spring Session (Redis or JDBC). This is the proper fix; Go stateless,…
  • Does choosing YAML over .properties affect performance? — Not in any way that matters. Configuration is parsed once at startup. YAML parsing is marginally slower, a matter of milliseconds, and it has zero runtime impact afterwards.
  • Which CI/CD tools do you use for continuous build and deployment? — For example.
  • What's your application's deployment structure? — Runtime: each microservice runs as a container in Kubernetes (EKS), as a Deployment with at least 3 replicas across AZs, an HPA, readiness and liveness probes, resource requests and limits, and a PodDisruptionBudget; Edge: a CDN, then a load balancer / ingress, then an API…
  • How do you create a pipeline in Jenkins? — Create a Pipeline (or Multibranch Pipeline) job that reads a Jenkinsfile from the repository, as pipeline as code.
  • A Jenkins pipeline fails intermittently. How do you diagnose and fix it? — Treat flakiness as a bug, not bad luck: Collect data. Which stage, which tests, which agents, and what time of day? Correlate the failures (test reports, a flaky-test tracker); Classify the cause:; Reproduce the failure by running the suspicious test in a loop; Fix the root…
  • Scenario: you must roll back a deployment because of a critical bug. What do you do? — Decide quickly to roll back, rather than attempt a risky hotfix, and communicate on the incident channel; Redeploy the last known-good artifact. Because images are immutable and versioned, this is quick:; Check the database compatibility. If the release ran a migration, the…
  • How do you secure sensitive information, such as API keys, in the deployment process? — Never in Git or images. Use secret scanning (gitleaks, GitHub push protection); Store secrets in a secrets manager (Vault, AWS Secrets Manager, Azure Key Vault, GCP Secret Manager); Inject them at runtime, as environment variables or mounted files, through the platform…
  • Describe automating deployments for a microservices architecture. — *"We had 18 services deployed by hand-run scripts, and releases took a day. I introduced a shared pipeline template (a reusable workflow), so each service repository got the same stages: build, test, SAST and dependency scans, image build with Jib, image scan, and pushing the…

Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions — open the lesson

  • How do you handle database migrations during deployments? — Manage schema changes as versioned migration scripts with Flyway or Liquibase, kept in the repository, reviewed, and applied automatically (at application startup, or as a separate pipeline step or Kubernetes Job before the rollout); Make them backward-compatible, using…
  • Scenario: the application must have zero downtime during deployments. What strategies do you use? — Rolling updates (the Kubernetes default), with maxUnavailable: 0 and maxSurge: 1, so capacity never drops; Readiness probes, so traffic only reaches pods that are warmed up; Graceful shutdown (server.shutdown=graceful, plus a preStop delay, so the load balancer stops…
  • Why do health checks matter in deployments, and how do you implement them? — Health checks let the platform decide automatically when to send traffic to an instance, and when to restart it. Without them, rollouts send users to instances that are still starting or already broken. Implement them with Spring Boot Actuator's probe groups: Readiness…
  • How do you manage configuration changes across environments? — One artifact, configuration injected per environment.
  • Scenario: you're deploying to the cloud for the first time. What should you keep in mind? — Architecture: stateless instances, managed databases and caches, object storage for files, and multiple AZs; Security: least-privilege IAM (roles, not access keys), private subnets, security groups, TLS everywhere, a secrets manager, encryption at rest, and WAF protection for…
  • How does containerisation with Docker improve deployments? — Consistency: the same image, with the runtime and dependencies included, runs in dev, CI and prod. No more "works on my machine"; Immutable, versioned artifacts: easy rollbacks, and an exact reproduction of what's running; Fast startup and density compared with VMs; Isolation…
  • Describe dealing with performance problems after a deployment. — *"Right after a release, p95 latency on the order API doubled, and database CPU rose sharply. The canary dashboards caught it.
  • Explain blue-green deployment and its advantages. — You keep two identical production environments. Blue serves users, and green receives the new version. Once green passes its smoke tests and health checks, the load balancer switches all traffic to green.
  • Scenario: your deployment process is too slow. How do you analyse and improve it? — Measure each stage (queue time, build, tests, image build, push, deploy, rollout, verification), then attack the largest ones: Build: dependency caches, build caches (Gradle, or the Maven extension), parallel modules; Tests: parallelise, split fast and slow suites, reuse…
  • Which monitoring tools do you use to check the health of deployed applications? — Metrics: Micrometer, then Prometheus (or a managed version), with Grafana dashboards and Alertmanager alerts (or Datadog or New Relic); Logs: structured JSON logs, shipped to the ELK/OpenSearch stack or Loki; Traces: OpenTelemetry, exported to Jaeger or Tempo; Uptime and…

JUnit 5 & Mockito

JUnit 5 — Interview Questions — open the lesson

  • What is JUnit, and why is it important? — JUnit is the standard testing framework for Java. It discovers test methods, runs them with a lifecycle, provides assertions, and reports the results to IDEs and build tools.
  • What's the difference between @Before and @BeforeClass? How are they used? — They're JUnit 4 annotations: @Before runs before each test method: fresh fixtures per test; @BeforeClass runs once before all tests in the class. It must be static, and is used for expensive shared setup.
  • How do you test for expected exceptions? — In JUnit 5, use assertThrows. It returns the exception, so you can also assert on its message or fields. (JUnit 4 used @Test(expected = …), or the ExpectedException rule.)
  • What's the difference between assertEquals, assertTrue and assertSame? — assertEquals(expected, actual) compares values with equals(), with a helpful failure message showing both values; assertTrue(condition) checks a boolean, but its failure message only says "expected true"; assertSame(expected, actual) checks reference identity (==).
  • What are parameterized tests, and how do they work? — One test method runs once per set of arguments. JUnit 5 uses @ParameterizedTest with sources: @ValueSource, @CsvSource and @CsvFileSource; @MethodSource; @EnumSource; @ArgumentsSource, for custom sources.
  • What is a test suite, and how do you create one? — A suite groups tests to run together, for example "all fast tests" or "the payment module". In JUnit 5, use the Platform Suite engine: @Suite with @SelectPackages, @SelectClasses, @IncludeTags or @ExcludeTags.
  • How do you handle timeouts? — JUnit 5's @Timeout(value = 2, unit = SECONDS) fails a test (or all tests in a class) that runs too long; assertTimeout runs the code in the same thread and fails after it finishes. assertTimeoutPreemptively aborts the code when time runs out, but beware: that code runs…
  • How do you structure a test case? — Arrange–Act–Assert (or Given–When–Then), with one behaviour per test, and a descriptive name that states the scenario and expected outcome.
  • What is the purpose of @Test? — It marks a method as a test that the engine should discover and run. JUnit 5 test methods can be package-private, must not be private or static, and return void.
  • How do you mock a static method? Is it possible without external libraries? — JUnit itself can't mock anything. It's a test runner, not a mocking library. Without extra libraries, the answer is design: wrap the static call behind an interface you can substitute (Clock, an IdGenerator, a CurrentTime provider), and inject it.
  • How do @RunWith and @Rule work? What replaced them? — In JUnit 4: @RunWith replaces the whole runner. For example, SpringRunner, MockitoJUnitRunner or Parameterized. Only one runner is allowed per class; @Rule / @ClassRule wrap each test (or the class) with reusable behaviour: TemporaryFolder, ExpectedException,…
  • How do you test private methods? Should you test them directly? — Test them through the public behaviour that uses them. Private methods are implementation details, and tests coupled to them break on every refactor.
  • How do you test a method that calls the database, without hitting the real database? — Separate the unit and integration concerns: Unit test the service logic with the repository mocked (Mockito), or with a simple in-memory fake. Fast and focused; Test the data access itself with a real database in a container (Testcontainers + @DataJpaTest). Queries,…
  • How does JUnit handle running tests in parallel? — JUnit 5 supports opt-in parallel execution through configuration (junit-platform.properties) — junit.jupiter.execution.parallel.enabled=true junit.jupiter.execution.parallel.mode.default=concurrent
  • What are the best practices for unit tests with JUnit? — Fast, isolated, repeatable and self-validating (FIRST). No sleeps, no real network, no dependency on test order; One behaviour per test, with descriptive names, and Arrange–Act–Assert; Test edge cases and failure paths, not just the happy path; Use fluent assertions…

Mockito Basics — Interview Questions — open the lesson

  • What is Mockito, and why is it used in unit testing? — Mockito is a mocking framework. It creates test doubles for a class's collaborators, so you can test the class in isolation.
  • How do you mock an object in Mockito? — Use Mockito.mock(Type.class), or declare @Mock fields with MockitoExtension. An unstubbed mock returns defaults: null, 0, false, empty collections and Optional.empty().
  • What are @Mock and @InjectMocks for? — @Mock creates a mock field. @InjectMocks creates the object under test, and injects the @Mock (and @Spy) fields into it: through the biggest constructor first, then setters, then fields.
  • How do you use when and thenReturn? — when(mock.method(args)).thenReturn(value) stubs a call. You can chain several values for consecutive calls, match arguments with matchers, or compute the answer with thenAnswer.
  • What's the difference between mock() and spy()? — A mock is a complete fake: every method does nothing, or returns a default, unless stubbed. A spy wraps a real object: methods run the real code unless you stub them.
  • How do you mock a method that returns void? — Mocks already do nothing for void methods, so usually no stubbing is needed. Just verify the call. To change the behaviour, use the do…() family — doThrow(new MailException("SMTP down")).when(mailer).send(any(Email.class));
  • What are doReturn(), doThrow() and doAnswer() used for? — The do…().when(mock).method() form is needed when when(mock.method()) can't be used: Void methods: when() needs a return value to wrap; Spies: it avoids calling the real method during stubbing; Re-stubbing a method that currently throws.
  • How do you verify a mock's behaviour? — Use verify(mock).method(args), optionally with a count (times(n), never(), atLeastOnce(), atMost(n)), argument matchers, ordering (inOrder), or timeouts for async code (timeout(500)).
  • How do you simulate an exception with Mockito? — For non-void methods, use when(mock.method()).thenThrow(new X(...)), or thenThrow(X.class). For void methods, use doThrow(...).when(mock).method().
  • How does ArgumentCaptor work? Give an example. — ArgumentCaptor captures the arguments passed to a mock, so you can make detailed assertions about objects your code builds internally, for example the entity passed to save(), or the message passed to send().

Mockito Advanced & Tricky Questions — Interview Questions — open the lesson

  • How do you mock static methods with Mockito? — Use Mockito.mockStatic(Type.class) in a try-with-resources block. The mock applies only to the current thread, and only inside the block.
  • What's the difference between verify() and verifyNoMoreInteractions()? — verify(mock).m() asserts that a specific interaction happened. verifyNoMoreInteractions(mock) asserts that there were no interactions left unverified on that mock.
  • How do you mock final classes and methods? Was it possible in older Mockito? — Mockito 2.1 introduced the inline mock maker (opt-in, through mock-maker-inline or the mockito-inline artifact), which uses a Java agent and instrumentation to mock final classes and methods.
  • How do you mock dependencies that are passed to a method as parameters? — Create the mock yourself, and pass it in as the argument. No injection magic is needed. Stub it, call the method, then verify.
  • How do you handle method chaining, such as foo.bar().baz()? — Stub each link, returning a mock for the intermediate objects. Or use RETURNS_DEEP_STUBS (see Q8). But mocking long chains is a strong sign of a Law of Demeter violation: the code under test knows too much about object internals.
  • What's the difference between a stub and a mock? — Both are test doubles: A stub provides canned answers, so the code under test can run. You assert on the result or state of the system under test; A mock is used to verify interactions: which calls happened, with what arguments, how many times. The test fails if the expected…
  • How do you mock objects when the class under test uses constructor injection? — Create the mocks, and pass them to the constructor directly. That's the simplest and most explicit option, and the compiler flags missing dependencies.
  • What is RETURNS_DEEP_STUBS, and when would you use it? — mock(Type.class, RETURNS_DEEP_STUBS) makes every method in a chain automatically return another mock, so when(a.b().c().d()).thenReturn(x) works without stubbing each level.
  • How do you control behaviour that depends on randomness, such as Math.random()? — Make the randomness a dependency. Inject a RandomGenerator (Java 17's interface), a Random with a fixed seed, or your own IdGenerator/Dice interface.
  • How do you combine JUnit and Mockito to write comprehensive unit tests? — JUnit 5 provides the structure (lifecycle, parameterized tests, assertions, nested scenarios), and Mockito provides the isolation (stubbing collaborators, verifying the important interactions). A comprehensive test class covers: the happy path; boundary values…

Follow-up questions this topic invites — and their answers

Q: How should I use this list in the last week before an interview? A: Do one pass per day. Cover the answer text, say your answer out loud, then check it. Mark every question you could not answer crisply, and spend your study time only on the marked ones by opening the linked full answer. By the third pass the marked list should be short.

Q: The interviewer asks one of these basics — should I give only the one-liner? A: Lead with the one-liner, then add one concrete detail or example from your own work. At this level the follow-up usually probes the mechanism behind the basic answer, so be ready to go one layer deeper using the key points in the full lesson.

Q: Some answers here were corrected compared with common prep sheets — why? A: Several widely shared answers are outdated or wrong (for example, Java version details, removed Spring APIs, or SQL queries that miss edge cases). The full lessons call these out under "Common trap" — reading those is the fastest way to stand out from candidates who memorised the same sheets.

Previous

Revise: Spring Framework, Spring Boot & Security (2–5 Years Tier)

Next

Advanced OOP & Design Scenarios — Interview Questions

AI Tutor

Lesson: Revise: Kafka, Git/Maven/Gradle, Deployment & Testing (2–5 Years Tier)

Quick actions

AI responses can be inaccurate. Verify critical information.