Maven Interview Questions and Answers

Maven interview questions with sample answers for 2026: POM, lifecycle, dependency scopes, plugins, BOM, Wrapper, and CI troubleshooting for experienced Java and DevOps roles.

Published

Updated

Read time 36 min read

Reviewed byDeepak Prasad

Maven Interview Questions and Answers

Maven interviews focus on how you structure Java builds—POM files, dependency scopes, lifecycle phases, plugins, and the errors that show up in CI. Below are 55 questions with sample answers grouped by topic, including modern practices for reproducible builds with the Maven Wrapper and BOM imports.

Pair this with Java interview questions (part one) when the loop mixes language and build tooling, and with Selenium interview questions when the role is Java test automation (TestNG, WebDriver, Maven surefire).


Interview context and how to prepare

What do Maven interviews test?

Interviewers want proof you can own the build, not only run mvn package. Expect questions across four layers:

Layer Typical questions
POM structure Coordinates, packaging, parent POM, dependencyManagement
Lifecycle Phases from validate through deploy; which plugin binds where
Dependencies Scopes, transitive resolution, exclusions, optional deps, BOMs
CI/CD Reproducible builds, Wrapper, caching, skipTests pitfalls

Java backend and DevOps roles both ask Maven—often alongside Gradle comparison questions. Senior loops add multi-module reactors, enforcer rules, and debugging classpath conflicts with mvn dependency:tree.

What is a realistic Maven prep plan?

Hands-on practice beats reading XML. A focused two-to-three week plan:

Week Focus Practice exercise
1 Multi-module project; read effective POM mvn help:effective-pom on a parent + child
2 Dependency scopes, enforcer, dependency:tree Introduce a version conflict and fix it
3 Plugins, profiles, Wrapper, CI — compiler, surefire, jar Pin plugin versions; add Maven Wrapper; run -Dtest= filters

Break a build on purpose (wrong scope, duplicate JAR, missing exclusion) and fix it with mvn dependency:tree and mvn -e. Say answers aloud using the lifecycle phase names interviewers expect.


Maven fundamentals

What is Maven?

Apache Maven is an open-source build and project-management tool from the Apache Software Foundation. It automates compiling, testing, packaging, and publishing Java projects using a declarative Project Object Model (pom.xml) rather than hand-written build scripts.

Maven is not just a compiler—it orchestrates the build: it resolves dependencies from repositories, runs plugins bound to lifecycle phases, and produces repeatable artifacts (JAR, WAR, EAR, etc.). Teams also use it for site generation, reporting, and release workflows.

Concern How Maven handles it
Build Lifecycle phases + plugins (compile, test, package)
Dependencies Declared in POM; resolved transitively from repositories
Structure Convention over configuration (src/main/java, src/test/java)
Releases install / deploy phases publish to local or remote repos

A strong answer is:

Maven is an Apache build and project-management framework that uses a POM to compile, test, package, and publish Java projects with convention-based layout and centralized dependency resolution.

What are the main features of Maven?

Maven combines a standard project layout, dependency management, and a plugin-driven lifecycle so teams spend less time wiring builds and more time shipping code.

Feature Interview angle
Convention over configuration Default directory layout and lifecycle phases work out of the box
Dependency management Transitive resolution, scopes, and version alignment via BOMs
Multi-module builds Parent POM + reactor builds coordinate related artifacts
Extensible plugins Goals (MOJOs) bind to phases—compiler, surefire, jar, deploy, etc.
Repository integration Local cache + Maven Central + corporate Nexus/Artifactory
Reporting & site Javadoc, checkstyle, and project-site generation via plugins

Because every Maven project follows the same mental model, onboarding is faster: a developer who knows one Maven repo can navigate another without relearning the build.

A strong answer is:

Maven gives you standardized project structure, declarative dependency management, plugin-driven lifecycle phases, multi-module support, and integration with local and remote repositories.

What areas of a Project can you manage by using Maven?

Maven is broader than a compile tool—it manages the full software delivery pipeline around a Java project.

Area Maven capability
Build Compile source, process resources, package deployable artifacts
Testing Unit tests (Surefire), integration tests (Failsafe), coverage reports
Release Versioning, tagging, and deployment via release plugin + deploy phase
Reporting Javadoc, dependency analysis, checkstyle, site reports
SCM integration SCM plugin ties builds to Git/SVN for release and changelog
Documentation Site plugin generates project documentation sites
Distribution distributionManagement targets internal or public repositories

In practice, CI pipelines call Maven for the repeatable core—mvn verify or mvn deploy—while Maven handles dependency resolution and artifact naming consistently.

A strong answer is:

Maven manages build, testing, release, reporting, SCM hooks, documentation, and artifact distribution through a single POM-driven workflow.

What are the main advantages of Maven?

Maven reduces build friction by replacing bespoke Ant scripts with shared conventions and declarative configuration.

Shared project structure — Every Maven project uses src/main/java, src/test/java, and pom.xml. Developers can jump between codebases without deciphering custom folder layouts.

Modular design — Multi-module reactors split large systems into manageable artifacts with one parent POM governing versions and plugin configuration.

Centralized dependency management — Dependencies are declared once in the POM; Maven downloads them from repositories instead of checking JARs into version control. Transitive dependencies resolve automatically.

Fewer non-coding decisions — Directory names, default phases, and plugin bindings come from conventions and the Super POM, so teams focus on application logic rather than reinventing build steps.

A strong answer is:

Maven standardizes project layout, supports modular multi-module builds, centralizes dependency resolution, and removes repetitive build configuration through conventions and inherited defaults.

Why do we say “Maven uses convention over configuration”?

Convention over configuration means sensible defaults replace boilerplate setup. Maven ships with opinions backed by years of Java practice—if you follow them, the build works with minimal XML.

Examples of Maven conventions:

Convention Default
Source code src/main/java
Test code src/test/java (not src/main/test)
Resources src/main/resources, src/test/resources
Output target/
Build descriptor pom.xml at project root

You can override paths in the POM, but most projects never need to. Contrast this with Ant, where every copy-and-compile step is explicit. Maven assumes you want the standard layout unless you say otherwise.

A strong answer is:

Maven uses convention over configuration because it provides proven defaults for directory layout, lifecycle phases, and plugin bindings so developers configure only what differs from the norm.

What are the responsibilities of a Build tool like Maven?

A build tool like Maven automates the path from source code to deployable artifacts and keeps that path repeatable across machines and CI agents.

Responsibility Maven example
Code generation Plugins generate sources from templates (e.g., JAXB, protobuf)
Documentation mvn javadoc:javadoc produces API docs from source
Compilation Compiler plugin compiles src/main/java to target/classes
Testing Surefire runs unit tests; Failsafe runs integration tests
Packaging Jar/War/EAR plugins produce distributable artifacts
Deployment install copies to local repo; deploy publishes to remote repo

Maven also resolves third-party libraries, enforces dependency scopes, and runs quality checks in the verify phase—tasks that would be error-prone if done manually.

A strong answer is:

A build tool compiles source, runs tests, packages artifacts, generates documentation, and deploys releases—Maven handles all of this through lifecycle phases and plugins bound to a declarative POM.

What are the differences between Ant and Maven?

Ant and Maven both build Java projects, but they represent different eras of build automation.

Dimension Apache Ant Apache Maven
Model Procedural XML tasks (<javac>, <copy>) Declarative POM + lifecycle phases
Structure No enforced layout; you define everything Convention: src/main/java, src/test/java
Dependencies Manual JAR classpath management Declarative <dependencies> with transitive resolution
Lifecycle You sequence targets yourself Built-in phases: validate → compile → test → package → install → deploy
Reusability Copy build.xml per project Plugins and parent POMs shared across projects
Learning curve Flexible but verbose Opinionated; faster once conventions are understood

Ant remains useful for highly custom, non-standard builds. Maven dominates greenfield Java because dependency management and multi-module coordination are first-class.

A strong answer is:

Ant is a procedural task toolkit with no enforced structure; Maven is declarative, convention-based, with built-in lifecycles, dependency management, and reusable plugins.

What is MOJO in Maven?

MOJO stands for Maven plain Old Java Object. It is the Java class that implements a single executable goal inside a Maven plugin.

Each MOJO declares metadata—goal name, default lifecycle phase, required parameters—and Maven invokes it when you run a goal like compiler:compile or when a phase triggers a bound plugin.

text
Plugin (e.g., maven-compiler-plugin)
  └── MOJO: compile goal
  └── MOJO: testCompile goal

When you run mvn test, Maven reaches the test phase, which binds the Surefire plugin's MOJO to execute unit tests. Understanding MOJOs helps in interviews because "plugin" is the packaging unit and "goal/MOJO" is the unit of work.

A strong answer is:

A MOJO is a Maven plain Old Java Object—the Java class behind a plugin goal that Maven executes during a lifecycle phase or when you invoke the goal directly.


Repositories and artifact storage

What is a Repository in Maven?

A Maven repository is a storage location for build artifacts, POM files, and metadata that Maven uses to resolve dependencies and publish releases.

When you declare a dependency in pom.xml, Maven looks up the artifact coordinates, downloads the JAR and its POM from a repository, caches them locally, and adds them to the compile or test classpath. Your own project's output is also stored as an artifact after mvn install.

Repositories are organized by coordinates: groupId/artifactId/version/ with the artifact file and checksums alongside.

A strong answer is:

A Maven repository stores artifacts, POMs, and metadata so Maven can download dependencies and publish built packages using coordinate-based directory layout.

What are the different types of repositories in Maven?

Maven distinguishes three repository roles in the resolution chain:

Type Location Purpose
Local ~/.m2/repository on your machine Cache of downloaded and locally installed artifacts
Central repo.maven.apache.org Public default remote repo for open-source libraries
Remote (custom) Corporate Nexus/Artifactory or vendor repos Private artifacts, mirrors, or air-gapped caches

Resolution order: Maven checks the local repository first. Missing artifacts are fetched from remote repositories configured in the POM or settings.xml (often via a mirror of Maven Central).

A strong answer is:

Maven uses a local cache on disk, Maven Central as the default public remote repository, and optional custom remote repos for private or mirrored artifacts.

What is a local repository in Maven?

The local repository is Maven's on-disk cache—typically ~/.m2/repository on Linux/macOS and %USERPROFILE%\.m2\repository on Windows.

Every dependency Maven downloads is stored here so subsequent builds skip network calls. Running mvn install also copies your project's artifact into the local repo, making it available as a dependency to other projects on the same machine via matching coordinates.

You can change the location in settings.xml:

xml
<localRepository>/path/to/custom/repo</localRepository>

Clearing or corrupt entries in .m2 is a common troubleshooting step when checksum or snapshot resolution errors appear.

A strong answer is:

The local repository is Maven's per-machine cache—defaulting to ~/.m2/repository—where downloaded and installed artifacts are stored for reuse across projects.

What is a central repository in Maven?

Maven Central—hosted at repo.maven.apache.org—is the default public remote repository for open-source Java artifacts.

It holds millions of JARs and POMs indexed by groupId, artifactId, and version. When your POM declares a dependency without a <repository> override, Maven resolves it from Central (directly or through a corporate mirror).

Central is read-heavy infrastructure: builds worldwide pull artifacts from it or from mirrors. It is not a general-purpose file dump—artifacts are immutable once published under a release version.

A strong answer is:

Maven Central at repo.maven.apache.org is the default public remote repository where open-source artifacts are published and resolved by coordinate.

What is a Remote repository in Maven?

A remote repository is any repository accessed over the network (or a mounted file URL) that is not the local cache.

Example Use case
Maven Central Public open-source libraries
Corporate Nexus / Artifactory Internal libraries, approved third-party caches
Vendor repo Spring, Red Hat, or other vendor-specific releases
<repository> in POM Project-specific extra repos (use sparingly)

Remote repos are declared in the POM or, preferably for mirrors and credentials, in settings.xml. Maven fetches missing artifacts from remotes and stores copies in the local repository.

A strong answer is:

A remote repository is a network-accessible artifact store—Central, a corporate proxy, or a vendor repo—that Maven queries when an artifact is not in the local cache.

Why should binaries not be stored in version control instead of a Maven repository?

Binary JARs belong in artifact repositories, not in Git, CVS, or Subversion. Version control is optimized for text diffs and merge workflows—not large immutable binaries.

Problem with VCS binaries Repository approach
Repository bloat Same Spring JAR duplicated across branches and modules
Slow clones/checkouts Large binary history inflates every clone
No transitive resolution You manually track dependency trees
Wrong versioning model Binaries rarely change in place; coordinates do

The POM declares coordinates; Maven downloads the exact artifact from a repository. That keeps source repos lean and builds reproducible.

A strong answer is:

Binaries bloat version control, slow checkouts, and lack transitive metadata—Maven repositories store artifacts once by coordinate while the POM in Git stays small and declarative.

Can anyone upload JARS or artifacts to Central Repository?

No. Maven Central is not an open upload endpoint. Publishers now use the Central Publisher Portal: verify a namespace, meet Maven Central requirements (valid POM, sources, javadoc where applicable), and publish GPG-signed artifacts. The older Sonatype OSSRH workflow reached end of life in June 2025; existing publishers migrated to the portal.

For Maven-based publishing, use Sonatype's central-publishing-maven-plugin or the current Central Portal workflow—both replace the legacy OSSRH staging flow.

Corporate teams typically publish to an internal Nexus or Artifactory instead. Central is for vetted open-source releases consumed by the global Java ecosystem.

A strong answer is:

Anyone cannot upload to Maven Central—you register through the Central Publisher Portal, verify your namespace, sign artifacts with GPG, and meet Central requirements; private releases go to internal repository managers.


POM, lifecycle, and coordinates

What is a POM?

POM stands for Project Object Model. It is the fundamental unit of configuration in Maven—an XML file named pom.xml at the project root.

The POM describes project coordinates (groupId, artifactId, version), packaging type, dependencies, plugin configuration, modules, profiles, and build settings. Maven reads the POM (merged with parent and Super POM) to know what to compile, which dependencies to resolve, and which goals to run.

Multi-module projects use a parent POM with <modules> listing child projects; each child inherits shared dependency and plugin management.

A strong answer is:

The POM is Maven's Project Object Model—an XML descriptor that defines coordinates, dependencies, plugins, and build configuration for a project.

What is Super POM?

The Super POM is Maven's built-in default POM that every project inherits implicitly. Even a minimal pom.xml with only coordinates gets default plugin bindings, directory paths, and repository definitions from the Super POM.

View effective defaults with:

bash
mvn help:effective-pom

The Super POM and Maven's default lifecycle provide inherited defaults such as standard directories (src/main/java, src/test/java), output location (target/), repositories, and default lifecycle behavior. Child POMs and parent POMs override or extend these values.

In real projects, pin plugin versions explicitly in pluginManagement to avoid surprises—effective plugin resolution also depends on lifecycle bindings and parent POMs, not only the Super POM.

A strong answer is:

The Super POM is Maven's built-in default configuration—all POMs inherit standard directories, lifecycle bindings, and repository defaults unless overridden; I still pin plugin versions in pluginManagement for reproducible builds.

What are the main required elements in POM file?

Every Maven POM must include the root element and Maven model version plus the three coordinates that uniquely identify the artifact:

xml
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>my-app</artifactId>
  <version>1.0.0-SNAPSHOT</version>
</project>
Element Role
modelVersion POM schema version (4.0.0 is the common model used by Maven 2/3 projects and still supported by Maven 4; upgrade to 4.1.0 only when you need Maven 4-specific features)
groupId Organization or group namespace (often reverse DNS)
artifactId Project or module name
version Release or snapshot version string

Optional but common: <packaging> (default jar), <name>, <description>, <dependencies>, and <build>.

A strong answer is:

A valid POM requires modelVersion, groupId, artifactId, and version—the coordinates Maven uses to identify and publish the artifact.

What are the phases in Build lifecycle in Maven?

The default build lifecycle defines an ordered sequence of phases. Maven runs each phase and any earlier phases when you invoke a later one (e.g., mvn package runs through package inclusive).

Full default lifecycle includes: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy.

For interviews, focus on the main phases:

Phase What happens
validate Verify POM and project structure are valid
compile Compile main source (src/main/java)
test Run unit tests (Surefire)
package Create JAR/WAR/EAR in target/
verify Integration-test checks and quality gates
install Install artifact into local repository
deploy Publish artifact to remote repository

Plugins bind their goals to these phases—you rarely invoke phases individually.

A strong answer is:

The default lifecycle runs ordered phases from validate through deploy; interviews focus on compile, test, package, verify, install, and deploy as the core build pipeline.

What command will you use to package your Maven project?

Use the package lifecycle phase:

bash
mvn package

This runs all phases up to and including package—compile, test, and then jar/war the output into target/. It does not install to the local repo (use mvn install) or publish remotely (use mvn deploy).

Common variants:

Command Effect
mvn package Build artifact after tests
mvn package -DskipTests Package without running tests
mvn clean package Delete target/ first, then package

Note: the correct flag is -DskipTests or -Dmaven.test.skip=true, not mvn -package.

A strong answer is:

Run mvn package to compile, test, and create the distributable artifact in target/; add clean to wipe previous output first.

What is the format of a Maven artifact coordinate?

Maven identifies artifacts with coordinates in this format:

text
groupId:artifactId:version[:packaging][:classifier]
Part Example Notes
groupId org.springframework.boot Namespace, often reverse DNS
artifactId spring-boot-starter-web Project or module name
version 3.2.0 Release or snapshot version
packaging jar Optional; defaults to jar
classifier sources Optional; distinguishes variants (sources, javadoc)

Examples:

  • com.example:my-app:1.0.0 — default JAR
  • com.example:my-app:1.0.0:war — WAR packaging
  • com.example:my-app:1.0.0:jar:sources — sources classifier

In dependency declarations, packaging and classifier appear as XML elements rather than colon-separated segments.

A strong answer is:

Maven artifact coordinates follow groupId:artifactId:version with optional packaging and classifier—uniquely identifying every JAR, POM, or variant in a repository.

What are the three main build lifecycles of Maven?

Maven defines three independent build lifecycles. Each lifecycle has its own sequence of phases; you invoke a phase and Maven runs that phase plus all earlier phases within the same lifecycle.

Lifecycle Purpose Example invocation
clean Remove artifacts from previous builds mvn cleanpre-clean, clean, post-clean
default Build, test, package, and deploy the project mvn install → runs through install
site Generate and publish project documentation site mvn site / mvn site-deploy

The default lifecycle (sometimes called build) is what interviews emphasize—validate, compile, test, package, install, deploy. clean and site are separate lifecycles you combine as needed: mvn clean install.

A strong answer is:

Maven has three lifecycles—clean, default, and site—each with its own phase sequence; default handles compile through deploy, clean removes old output, site generates documentation.


Plugins, profiles, and settings

What is an Archetype in Maven?

An archetype is a project template packaged as a Maven artifact. It generates a new project skeleton—directory layout, sample POM, and starter source—so teams start from a consistent structure.

Archetypes encode organizational standards: multi-module layout, chosen dependencies, plugin configuration, and package naming. The maven-archetype-plugin lists available templates (e.g., maven-archetype-quickstart) and prompts for groupId, artifactId, and package name.

Using archetypes reduces ramp-up time and enforces convention over configuration from day one.

A strong answer is:

A Maven archetype is a reusable project template that scaffolds directory structure, POM, and starter code so new projects match team conventions immediately.

What is the command in Maven to generate an Archetype?

Generate a new project interactively from an archetype:

bash
mvn archetype:generate

Maven prompts for archetype selection (or filter by catalog), then groupId, artifactId, version, and package. For non-interactive CI or scripting, pass properties:

bash
mvn archetype:generate \
  -DgroupId=com.example \
  -DartifactId=my-app \
  -DarchetypeArtifactId=maven-archetype-quickstart \
  -DarchetypeVersion=1.5 \
  -DinteractiveMode=false

The plugin creates the project directory with standard src/main/java and src/test/java layout.

A strong answer is:

Use mvn archetype:generate to scaffold a new Maven project from a template, interactively or with -D properties for automation.

What are the main uses of a Maven plugin?

Maven itself is a plugin execution framework—nearly all build work is done by plugins binding goals (MOJOs) to lifecycle phases or invoked directly on the command line.

Plugin area Example plugin Typical goal
Compile maven-compiler-plugin compile, testCompile
Test maven-surefire-plugin test
Package maven-jar-plugin, maven-war-plugin jar, war
Clean maven-clean-plugin clean
Install/deploy maven-install-plugin, maven-deploy-plugin install, deploy
Reporting maven-javadoc-plugin, maven-checkstyle-plugin javadoc, checkstyle
Code quality maven-enforcer-plugin enforce rules

Configure plugin version and parameters in the POM <build><plugins> section. Pinning versions avoids surprises when the Super POM defaults change.

A strong answer is:

Maven plugins perform compile, test, package, clean, deploy, and reporting work by binding goals to lifecycle phases or running as standalone commands like mvn javadoc:javadoc.

How will you find the version of a plugin being used?

Maven resolves plugin versions from the Super POM, parent POM, pluginManagement, or an explicit <version> on the plugin. To see what is actually in effect for your project, use the Help plugin's describe goal with the plugin prefix (not the full artifact ID):

bash
mvn help:describe -Dplugin=compiler -Ddetail

Replace compiler with the prefix for any plugin (surefire, jar, install, etc.). Add -Dfull for even more detail.

Command What it shows
mvn help:describe -Dplugin=compiler -Ddetail Effective version, goals, default phase bindings
mvn help:effective-pom Full merged POM including all plugin versions
mvn help:describe -Dplugin=org.apache.maven.plugins:maven-compiler-plugin:3.13.0 Describe a specific coordinate

The -Ddetail flag lists goals and lifecycle bindings—useful when debugging "which compiler plugin version is CI using?"

A strong answer is:

I run mvn help:describe -Dplugin=compiler -Ddetail to see the resolved plugin version and bindings, or mvn help:effective-pom when I need the full merged configuration.

What are the different types of profiles in Maven and where are they defined?

Profiles let you vary build behavior (dependencies, properties, repositories, plugins) per environment or activation trigger.

Profile type Where defined Typical use
Per project pom.xml (<profiles>) Environment-specific deps, -Pprod activation
Per user ~/.m2/settings.xml Developer machine overrides (mirrors, credentials)
Global $MAVEN_HOME/conf/settings.xml Org-wide defaults on shared build agents

Older Maven 2 builds used profiles.xml, but it was removed in Maven 3. Use POM or settings profiles instead.

Activation triggers:

  • Command line: mvn -Pdev,integration-test
  • Properties: -Denv=prod matching <property><name>env</name><value>prod</value></property>
  • JDK version, OS family, or file presence

A strong answer is:

Project profiles live in pom.xml; user profiles in ~/.m2/settings.xml; global profiles in $MAVEN_HOME/conf/settings.xml. profiles.xml was removed in Maven 3—I use POM or settings profiles with -P or property activation.

Where are Maven settings.xml files located?

Maven reads two settings.xml locations and merges them (user settings override global defaults):

Location Path Purpose
Global (installation) $MAVEN_HOME/conf/settings.xml Defaults for all users on the machine
User ~/.m2/settings.xml Per-developer mirrors, servers, credentials, profiles

On Windows, ~/.m2 resolves to C:\Users\<username>\.m2\.

Related files in ~/.m2/:

File Role
repository/ Local artifact cache (not settings, but same directory)
settings-security.xml Encrypted server passwords (optional)
toolchains.xml JDK/tool paths for maven-toolchains-plugin

Use mvn help:effective-settings to see the merged result.

A strong answer is:

Global settings sit in $MAVEN_HOME/conf/settings.xml; per-user overrides in ~/.m2/settings.xml. User settings win on conflict—I verify with mvn help:effective-settings.

What are the main elements we can find in settings.xml?

settings.xml configures Maven runtime behavior—not project structure (that belongs in pom.xml).

Element Purpose
<localRepository> Override default ~/.m2/repository path
<interactiveMode> true (default) prompts for input; false for CI
<offline> true blocks remote downloads—useful in air-gapped builds
<mirrors> Redirect repository URLs (e.g., corporate Nexus mirror of Central)
<servers> Credentials for deployment repos (id must match pom.xml <repository><id>)
<proxies> HTTP proxy for corporate networks
<profiles> / <activeProfiles> User-level profile activation
<pluginGroups> Extra plugin group prefixes for shorthand goals

Example mirror (common in enterprises):

xml
<mirrors>
  <mirror>
    <id>corp-nexus</id>
    <mirrorOf>central</mirrorOf>
    <url>https://nexus.example.com/repository/maven-central</url>
  </mirror>
</mirrors>

A strong answer is:

Key settings elements are localRepository, mirrors, servers, proxies, profiles, and activeProfiles—mirrors and server credentials are what I check first when CI cannot reach Central.


Installation and project layout

How will you check the version of Maven in your system?

Run:

bash
mvn -version

(or mvn -v or mvn --version)

Sample output:

text
Apache Maven 3.9.x
Maven home: /opt/maven
Java version: 21.0.2, vendor: Eclipse Adoptium
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "6.8.0", arch: "amd64"

This confirms Maven version, Maven home, and the JDK Maven will use—critical when debugging "wrong Java" build failures.

Situation What to check
Multiple Maven installs Compare mvn -version vs which mvn / where mvn
Wrapper project ./mvnw -version — may differ from global mvn
CI drift Pin with Maven Wrapper instead of relying on agent image

A strong answer is:

mvn -version reports Maven version, Maven home, and the Java runtime in use—I use it before blaming plugin or compiler errors on the wrong JDK.

How will you verify if Maven is installed on Windows?

Quick check — open Command Prompt or PowerShell:

powershell
mvn -version

If Maven is on PATH, you see version, Maven home, and Java details.

If the command is not found:

Step Action
1 Confirm MAVEN_HOME or M2_HOME points to the install directory
2 Confirm %MAVEN_HOME%\bin is in PATH
3 Open a new terminal after changing environment variables
4 Verify java -version works—Maven requires a JDK

Alternative on a Wrapper project:

powershell
.\mvnw.cmd -version

Wrapper projects do not require a global Maven install.

A strong answer is:

I run mvn -version in cmd or PowerShell; if it fails I check MAVEN_HOME\bin on PATH and that Java is installed. On Wrapper projects I use mvnw.cmd instead.

What is a Maven artifact?

An artifact is a file published to or resolved from a Maven repository—most often a JAR, but also WAR, EAR, ZIP, or a POM.

Coordinates uniquely identify an artifact:

text
groupId:artifactId:version[:packaging][:classifier]

Example: org.apache.commons:commons-lang3:3.14.0:jar

Concept Meaning
groupId Organization or project namespace (org.springframework.boot)
artifactId Module or library name (spring-boot-starter-web)
version Release (1.0.0) or snapshot (1.0.0-SNAPSHOT)
packaging jar (default), war, pom, etc.
classifier Variant (sources, javadoc, tests)

When you declare a <dependency>, you reference an artifact. When mvn package runs, Maven produces artifacts (e.g., target/myapp-1.0.0.jar) and mvn install copies them to the local repository.

A strong answer is:

A Maven artifact is a deployable file—usually a JAR—identified by GAV coordinates. Dependencies reference artifacts; the build produces and installs artifacts to the local or remote repository.

Where will you find the class files after compiling a Maven project successfully?

After mvn compile (or any phase that compiles main sources), compiled .class files land in:

text
${project.basedir}/target/classes/

Related output directories:

Phase / goal Output location
compile target/classes/
test-compile target/test-classes/
package target/<artifactId>-<version>.jar (plus target/classes/ inside)
clean Removes entire target/ directory

The path is driven by ${project.build.outputDirectory} (default target/classes). Custom layouts require explicit POM configuration—see question 50.

A strong answer is:

Main compiled classes go to target/classes/; test classes go to target/test-classes/. mvn clean wipes the whole target/ folder.

What are the default locations for source, test and build directories in Maven?

Maven's convention over configuration defaults:

Directory role Default path POM property
Main sources src/main/java ${project.build.sourceDirectory}
Main resources src/main/resources ${project.build.resources}
Test sources src/test/java ${project.build.testSourceDirectory}
Test resources src/test/resources ${project.build.testResources}
Build output target/ ${project.build.directory}

Other conventional roots:

  • src/main/webapp — WAR projects
  • src/site — Maven site documentation

These defaults come from the Super POM. Override only when you have a legacy layout—and prefer migrating to standard directories when possible.

A strong answer is:

Defaults are src/main/java, src/test/java, and target/ for build output. I only override sourceDirectory or use build-helper-maven-plugin when legacy code cannot move.

What is the result of jar:jar goal in Maven?

The jar:jar goal (from maven-jar-plugin, bound to the package phase by default) creates a JAR from already-compiled classes.

Output:

text
target/${project.build.finalName}.jar

Default finalName is ${project.artifactId}-${project.version} → e.g. myapp-1.0.0.jar.

Behavior Detail
Does not recompile Expects target/classes/ to exist from compile
Includes Compiled classes + processed src/main/resources
Excludes Test classes (target/test-classes/) unless configured otherwise
Manifest Default manifest; customize via maven-jar-plugin <configuration>

Run explicitly: mvn jar:jar — or simply mvn package, which runs jar:jar automatically for packaging=jar projects.

A strong answer is:

jar:jar packages compiled classes from target/classes/ into target/<artifactId>-<version>.jar during the package phase—it does not recompile sources.


Dependency management

What are the different dependency scopes in Maven?

Dependency scope controls classpath visibility and whether the dependency is propagated transitively.

Scope Compile classpath Test classpath Runtime classpath Transitive Typical example
compile (default) commons-lang3, internal libraries
provided javax.servlet-api (container supplies at runtime)
runtime JDBC driver needed only at runtime
test JUnit, Mockito
system Local JAR via <systemPath>avoid; not from a repo
import BOM import in <dependencyManagement> only (type=pom)

provided scope: Provided dependencies are generally not included in the runtime classpath of downstream consumers—the practical interview answer, even though Maven's transitivity rules are more nuanced by dependency path.

import scope does not add a dependency—it merges version constraints from a BOM POM into dependencyManagement. Used heavily with Spring Boot and platform BOMs.

Verify effective scopes on the classpath with:

bash
mvn dependency:tree -Dverbose

A strong answer is:

Six scopes: compile, provided, runtime, test, system, and import. Compile is default and transitive; provided and test are not on the runtime classpath; import is BOM-only in dependencyManagement—I confirm conflicts with mvn dependency:tree.

How can we exclude a dependency in Maven?

Use <exclusions> inside a direct <dependency> to block a transitive artifact from entering your classpath.

xml
<dependencies>
  <dependency>
    <groupId>com.example</groupId>
    <artifactId>library-a</artifactId>
    <version>2.0.0</version>
    <exclusions>
      <exclusion>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
      </exclusion>
    </exclusions>
  </dependency>
</dependencies>
Rule Detail
Exclusions are not inherited Each POM that needs the exclusion must declare it (or use dependencyManagement)
No version on exclusion Match by groupId + artifactId only
Does not exclude children Excluding A does not exclude A's other transitive deps unless they are only reachable through A

Verify the exclusion worked:

bash
mvn dependency:tree | grep slf4j

For duplicate version conflicts, also consider maven-enforcer-plugin with dependencyConvergence or requireUpperBoundDeps.

A strong answer is:

I add <exclusions> under the direct dependency that pulls the unwanted transitive JAR, then confirm with mvn dependency:tree. For recurring conflicts I use enforcer rules or BOM alignment.

How Maven searches for JAR corresponding to a dependency?

Maven resolves artifacts in a defined order:

  1. Local repository (~/.m2/repository by default) — if the exact GAV exists, download is skipped
  2. Remote repositories — declared in pom.xml, parent POM, or settings.xml mirrors
  3. Download and cache — artifact is stored locally for reuse

Resolution steps (simplified):

text
pom.xml dependency (GAV)
    → merge dependencyManagement / BOM imports
    → apply exclusions and optional flags
    → resolve transitive graph
    → check local repo
    → fetch missing artifacts from remote(s)
    → store under ~/.m2/repository/<groupId path>/<artifactId>/<version>/
Tool Use
mvn dependency:tree See resolved graph and conflict hints
mvn dependency:resolve Force resolution and display paths
mvn dependency:purge-local-repository Clear cached copy of a dependency (rare troubleshooting)

Mirrors in settings.xml can redirect all Central traffic to an internal proxy. SNAPSHOT artifacts re-resolve on a TTL (default: daily check for updates).

When multiple versions of the same artifact are reachable, Maven applies dependency mediation—commonly described as nearest definition wins. Use dependencyManagement or a BOM to control the version that ends up on the classpath.

A strong answer is:

Maven checks the local repo first, then remote repositories from the POM and settings mirrors, caching downloads under ~/.m2/repository. When versions conflict, nearest-wins mediation applies—I use dependency:tree and dependencyManagement or a BOM to verify the result.

What is a transitive dependency in Maven?

If project A depends on B, and B depends on C, then C is a transitive dependency of A—you did not declare C, but Maven pulls it automatically.

Example:

text
your-app → spring-boot-starter-web → spring-web → spring-core
Concept Detail
Automatic since Maven 2 Declare only direct dependencies in pom.xml
Scope propagation Transitive scopes are adjusted (e.g., compilecompile; provided not propagated)
Conflict resolution Nearest-wins on the dependency tree; version can differ from what you expect

Inspect the graph:

bash
mvn dependency:tree

Manage versions without repeating them in every module:

  • Parent dependencyManagement
  • BOM import scope
  • maven-enforcer-plugin to ban divergent versions

A strong answer is:

Transitive dependencies are libraries your direct dependencies pull in automatically. I inspect them with mvn dependency:tree and align versions via BOM or dependencyManagement, using enforcer when teams need hard guarantees.

What are Excluded dependencies in Maven?

An excluded dependency is a transitive artifact you explicitly remove from the dependency graph using <exclusions>.

Scenario: Library B brings in outdated commons-logging, but you standardize on SLF4J. You depend on B but exclude commons-logging.

xml
<dependency>
  <groupId>com.example</groupId>
  <artifactId>library-b</artifactId>
  <version>1.0</version>
  <exclusions>
    <exclusion>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
    </exclusion>
  </exclusions>
</dependency>
Point Detail
Local to the declaration Exclusion applies only on the dependency where you declare it
Not global Other paths to the same artifact may still pull it in—check the full tree
Alternative dependencyManagement + BOM to replace with a preferred version instead of excluding

After excluding, confirm nothing else reintroduces the JAR: mvn dependency:tree -Dincludes=commons-logging.

A strong answer is:

Excluded dependencies are transitive JARs I block with <exclusions> on a direct dependency. I always re-check dependency:tree because another path may still introduce the same artifact.

What are Optional dependencies in Maven?

Mark a dependency <optional>true</optional> when your library can use it but consumers should not inherit it transitively.

Example: A logging adapter library depends on both SLF4J and Log4j2 bindings, but only one is needed per consumer.

xml
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-core</artifactId>
  <version>2.23.1</version>
  <optional>true</optional>
</dependency>
Behavior Detail
Project B optional-dep on C Project A depending on B does not get C automatically
Consumer's choice A must explicitly declare C if it needs that feature
Unlike exclusion Optional is declared by the provider; exclusion by the consumer

Optional dependencies reduce classpath bloat for libraries with pluggable features.

A strong answer is:

Optional dependencies are not propagated transitively—the consumer must declare them explicitly. Library authors use <optional>true</optional> for pluggable features; consumers use exclusions to block unwanted transitives.


Testing, debugging, and releases

How can we get the debug or error messages from the execution of Maven?

Maven provides flags for progressively more detail:

Flag Level When to use
(none) INFO Normal builds
-e / --errors Print full stack traces for build failures First step when a goal fails
-X / --debug Debug logging (very verbose) Plugin resolution, classpath, wire-level repo access
-q / --quiet Minimal output CI logs when only pass/fail matters

Examples:

bash
mvn -e clean verify          # stack trace on failure
mvn -X clean verify            # full debug (large logs)
mvn -e -X clean verify         # both—use sparingly

Additional diagnostics:

bash
mvn dependency:tree            # classpath / version conflicts
mvn help:effective-pom         # merged POM surprises
mvn -Dmaven.repo.local=/tmp/repo verify   # isolate corrupt local cache

Combine -e for the exception and dependency:tree when the failure is a missing class or version clash.

A strong answer is:

I start with mvn -e for stack traces on failure; escalate to mvn -X for plugin and resolution debugging. For dependency issues I pair that with mvn dependency:tree.

What is the difference between a Release version and SNAPSHOT version in Maven?
Aspect SNAPSHOT (1.0.0-SNAPSHOT) Release (1.0.0)
Stability Work in progress Immutable, published
Downloads Can change day to day (timestamped builds) Same bits every time
Repository Deployed to snapshot repo (mutable) Release repo (immutable—redeploy blocked)
Use in production Discouraged Expected
Version progression 1.0.0-SNAPSHOT1.0.0 at release Next dev cycle starts 1.1.0-SNAPSHOT

SNAPSHOT resolution: Maven may check remote snapshots daily (-U forces update: mvn -U clean install).

Release workflow: maven-release-plugin bumps versions, tags SCM, and deploys non-SNAPSHOT artifacts.

CI tip: pin release versions in production builds; use snapshots only for internal integration branches.

A strong answer is:

SNAPSHOT versions are mutable integration builds; release versions are immutable and reproducible. I never deploy snapshots to production, and I use mvn -U when I need the latest snapshot from the remote repo.

How will you run test classes in Maven?

Unit tests run in the test phase via maven-surefire-plugin (default for JAR projects). Integration tests use maven-failsafe-plugin (integration-test / verify phases).

Run specific unit tests (Surefire):

bash
mvn test -Dtest=OrderServiceTest
mvn test -Dtest=Order*Test
mvn test -Dtest=OrderServiceTest#shouldCreateOrder
mvn test -Dtest=OrderServiceTest,PaymentServiceTest
Pattern Matches
OrderServiceTest Single class
Order*Test Prefix wildcard
OrderServiceTest#shouldCreateOrder Single test method (JUnit 4/5)

Integration tests (Failsafe):

bash
mvn verify -Dit.test=OrderApiIT

Surefire and Failsafe use different property names (-Dtest vs -Dit.test) and naming conventions—keep integration tests on Failsafe during verify, not mixed into loose Surefire package patterns.

Surefire does not recompile tests if sources are unchanged—run mvn test-compile test after editing test sources.

A strong answer is:

Surefire runs unit tests in the test phase—I use mvn test -Dtest=ClassName or method-level filters. Failsafe handles integration tests with mvn verify -Dit.test=OrderApiIT.

Sometimes Maven compiles the test classes but doesn't run them? What could be the reason for it?

test-compile succeeding but no tests executing usually points to Surefire configuration, not the compiler.

Cause What to check
Wrong -Dtest filter Typo or overly narrow pattern matches zero tests
Global test property Legacy settings.xml or POM property overriding Surefire's test parameter
<skipTests>true</skipTests> In maven-surefire-plugin config or profile
Includes/excludes Custom <includes> / <excludes> filtering out your naming pattern
No runnable tests Abstract classes, missing @Test, or JUnit 5 without junit-jupiter engine on classpath
Test phase skipped mvn compile test-compile only—does not invoke Surefire
Packaging / plugin missing Non-standard packaging without Surefire bound

Diagnose:

bash
mvn test -X 2>&1 | grep -i surefire
mvn surefire:test -Dtest=MyTest

Inspect effective config: mvn help:effective-pom | grep -A20 surefire

A strong answer is:

If tests compile but do not run, I check Surefire—-Dtest filters, skipTests, includes/excludes, and JUnit engine deps. mvn test -X shows which tests Surefire selected.

How can we skip the running of tests in Maven?

Two commonly confused properties—they are not equivalent:

Property Compiles tests? Runs tests? Typical use
-DskipTests=true Fast CI package when test sources should still compile
-Dmaven.test.skip=true Emergency skip—saves compile time too

Examples:

bash
mvn package -DskipTests
mvn install -Dmaven.test.skip=true

POM-level (discouraged for production pipelines):

xml
<plugin>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <skipTests>true</skipTests>
  </configuration>
</plugin>

Failsafe (integration tests) is configured separately: use -DskipITs=true or <skipITs> in maven-failsafe-plugin. -DskipTests is commonly used for unit-test skipping and may also be honored by Failsafe depending on plugin version and configuration, but many teams prefer skipITs to control integration tests separately.

Prefer -DskipTests for unit tests when you still want compile-time validation of test code.

A strong answer is:

-DskipTests=true is the usual unit-test skip and still compiles tests; -Dmaven.test.skip=true skips both compile and run. For integration tests I use Failsafe's skipITs rather than assuming skipTests covers both plugins.

Can we create our own directory structure for a project in Maven?

Yes, but Maven's defaults exist for a reason—override only for legacy code or generated sources.

Option 1 — Override standard directories in the POM:

xml
<build>
  <sourceDirectory>src/java</sourceDirectory>
  <testSourceDirectory>src/test</testSourceDirectory>
  <directory>out</directory>
  <outputDirectory>out/classes</outputDirectory>
</build>

Option 2 — Add extra source roots with build-helper-maven-plugin (preferred for additional folders):

xml
<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>build-helper-maven-plugin</artifactId>
  <executions>
    <execution>
      <id>add-source</id>
      <phase>generate-sources</phase>
      <goals><goal>add-source</goal></goals>
      <configuration>
        <sources>
          <source>src/generated/java</source>
        </sources>
      </configuration>
    </execution>
  </executions>
</plugin>
Approach Best for
<sourceDirectory> Single non-standard root replacing default
build-helper-maven-plugin Multiple extra source/test roots
Standard layout New projects—IDE and tooling support

A strong answer is:

Yes—set <sourceDirectory> / <testSourceDirectory> and <directory> in <build>, or add extra roots with build-helper-maven-plugin. For greenfield projects I stick to src/main/java and src/test/java.


Multi-module and build portability

What are the differences between Gradle and Maven?

Both orchestrate builds; they differ in model, flexibility, and ecosystem defaults.

Dimension Maven Gradle
Configuration XML POM, convention over configuration Groovy/Kotlin DSL, programmatic
Model Declarative; lifecycle phases + plugins Task graph; incremental and parallel by default
Flexibility Structured; custom logic needs plugins Highly customizable tasks and lazy configuration
Learning curve Steeper XML, predictable structure DSL learning curve, faster builds at scale
Ecosystem Dominant in Java enterprise, BOM patterns Android default, Kotlin-first shops
Dependency mgmt dependencyManagement, BOM import Platforms (enforcedPlatform), version catalogs
Reproducibility Maven Wrapper Gradle Wrapper

Many organizations run both—Maven for legacy services, Gradle for Android or Kotlin microservices. Knowing Maven's lifecycle maps helps when reading Gradle's maven-publish output.

A strong answer is:

Maven is XML-driven with fixed lifecycle conventions; Gradle is a flexible task-graph DSL with stronger incremental builds. I pick Maven for standardized Java enterprise multi-module repos and Gradle when Android or heavy customization dominates.

What is the difference between Inheritance and Multi-module in Maven?

Both use a parent POM, but they solve different problems.

Concept Parent inheritance (<parent>) Multi-module (<modules>)
Purpose Share config—plugin versions, dependencyManagement, properties Build multiple projects in one reactor
Relationship Child POM inherits from parent (can be external artifact) Aggregator lists modules to build together
Build command mvn install in child builds one module mvn install at root builds reactor order
Typical layout Spring Boot parent, corporate super-POM parent/ + api/, service/, web/ siblings

They combine often: a root aggregator POM with <modules> also acts as <parent> for children.

text
root-pom (packaging=pom)
  ├── <modules> → api, service, web
  └── <dependencyManagement> → inherited by children via <parent>

Inheritance alone does not require modules to live in the same repo—parent can be published to Nexus. Multi-module requires the aggregator to list each module path.

A strong answer is:

Inheritance shares POM configuration via <parent>; multi-module aggregates subprojects in one reactor via <modules>. Real projects usually use a parent aggregator that both inherits config and lists modules.

What is Build portability in Maven?

Build portability is how easily a project builds on a fresh machine or CI agent without undocumented local tweaks.

Portable build Non-portable build
git clone && ./mvnw verify works Requires manual settings.xml secrets not documented
Versions in POM or Wrapper Depends on developer's global Maven 3.6 vs 3.9
JDK pinned via Toolchains or CI matrix "Works only with JDK 8 installed at /usr/lib/..."
Dependencies from public or mirrored repos Manual mvn install:install-file for missing JARs

Improve portability:

  • Commit Maven Wrapper (mvnw)
  • Document required JDK version in POM (maven-compiler-plugin) and CI
  • Use .mvn/maven.config for shared flags
  • Avoid system scope dependencies
  • Store server credentials in CI secrets, not in committed settings.xml

A strong answer is:

A portable Maven build succeeds on any clean environment with only documented prerequisites—Wrapper, JDK version, and repo access. I avoid machine-specific paths, system-scope JARs, and undeclared settings.xml dependencies.


Modern Maven practices

What is the Maven Wrapper and why do teams use it?

The Maven Wrapper (mvnw / mvnw.cmd + .mvn/wrapper/) downloads and runs a project-pinned Maven distribution so everyone and CI uses the same version.

Generate (once):

bash
mvn wrapper:wrapper -Dmaven=<current-approved-maven-version>

Use the version approved by your team or CI image—not necessarily the newest release on publish day. Pin deliberately in .mvn/wrapper/maven-wrapper.properties so laptop and pipeline stay aligned.

Committed files:

File Role
mvnw, mvnw.cmd Unix/Windows launcher scripts
.mvn/wrapper/maven-wrapper.properties Pinned Maven version and download URL
.mvn/wrapper/* Wrapper metadata/bootstrap files, depending on wrapper type

Benefits:

  • Eliminates "CI has Maven 3.6, laptop has 3.9" drift
  • New developers run ./mvnw verify without installing Maven globally
  • Reproducible builds pair well with locked pluginManagement versions

Trade-offs: Wrapper files under .mvn/wrapper/ are typically committed; exact layout depends on wrapper type. First run downloads Maven to ~/.m2/wrapper/dists/.

Usage:

bash
./mvnw clean verify        # Linux/macOS
mvnw.cmd clean verify      # Windows

A strong answer is:

Maven Wrapper pins the Maven version per project—./mvnw downloads the right distribution so CI and developers stay aligned without a global Maven install.

How does a BOM (Bill of Materials) work in Maven?

A BOM is a POM with packaging=pom that lists dependencyManagement entries—version alignment without forcing every module to depend on every library.

Import a BOM:

xml
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-dependencies</artifactId>
      <version>3.4.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

Child module declares without version:

xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Concept Detail
import scope Merges BOM's dependencyManagement into yours—BOM itself is not a dependency
Version alignment Spring, JUnit, Jackson versions tested together by BOM authors
Overrides Explicit <version> on a child dependency wins over BOM
Verify mvn dependency:tree and maven-enforcer-plugin (dependencyConvergence)

Custom BOM pattern: publish com.example:example-platform-bom:1.0.0 from a parent project; all microservices import it.

A strong answer is:

A BOM is an imported POM (type=pom, scope=import) that centralizes dependency versions in dependencyManagement. Modules declare artifacts without versions; I validate alignment with dependency:tree and enforcer rules.


Quick reference: what to prioritize before the interview

Priority Topic Command or concept to rehearse
High Lifecycle phases validatecompiletestpackageinstalldeploy
High Dependency scopes compile, provided, runtime, test, import (BOM)
High Debugging classpath mvn dependency:tree, exclusions, enforcer
High Test skipping -DskipTests vs -Dmaven.test.skip
Medium Multi-module <parent> inheritance vs <modules> reactor
Medium Profiles & settings settings.xml mirrors, -P activation
Medium SNAPSHOT vs release -U for snapshots; immutability of releases
Medium Wrapper & BOM ./mvnw verify; scope=import BOM pattern
Lower Archetypes mvn archetype:generate
Lower Site lifecycle mvn site (less common in backend loops)

If time is short, master lifecycle + scopes + dependency:tree + skipTests distinction—those four cover most Maven screens for experienced Java roles.

Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …