Maven in Java
Maven in Java is the most widely used build tool for compiling code, downloading libraries, running tests and packaging applications. Instead of typing long javac and jar commands, you describe your project once in a pom.xml file, and Maven builds it the same way on every computer.
This lesson explains what Maven does, how to install it, the pom.xml file, the standard folder layout, coordinates, the build lifecycle, plugins and goals, and the commands you will use every day. It ends by building and running a small grade-report application as an executable JAR.
Why Use Maven in Java Projects
Without a build tool, you compile, test and package by hand, and you download every library JAR yourself. Maven automates all of it.
| Task | Without Maven | With Maven |
|---|---|---|
| Compile | javac -d out -cp lib/* src/com/gocourse/*.java | mvn compile |
| Get libraries | Download JARs and their dependencies by hand | Declare them in pom.xml; Maven downloads them |
| Run tests | Build a classpath and start the test runner yourself | mvn test |
| Create a JAR | jar --create --file app.jar --main-class ... | mvn package |
| Same build for the whole team | Shared notes and scripts | One pom.xml in version control |
Maven follows convention over configuration: if you put files where Maven expects them, you only need to configure what is different about your project. To see what Maven replaces, compare with JAR File in Java and Java Classpath.
Install Maven and Check the Version
Maven needs a JDK. Install the JDK first, then Maven:
# macOS (Homebrew)
brew install maven
# Linux or macOS (SDKMAN!)
sdk install maven
# Ubuntu / Debian (the packaged version can be older)
sudo apt install maven
# Windows: download the "Binary zip archive" from https://maven.apache.org/download.cgi,
# extract it (for example to C:\tools\apache-maven-3.9.16) and add its "bin" folder to PATH.
Check the installation:
mvn -v
Output (your paths and versions will differ):
Apache Maven 3.9.16
Maven home: /home/asha/.sdkman/candidates/maven/current
Java version: 25.0.1, vendor: Eclipse Adoptium, runtime: /home/asha/.sdkman/candidates/java/25.0.1-tem
Default locale: en_IN, platform encoding: UTF-8
OS name: "linux", version: "6.8.0-48-generic", arch: "amd64", family: "unix"
How it works:
mvn -vprints the Maven version and the JDK Maven will use. If the Java version is wrong, set theJAVA_HOMEenvironment variable to the right JDK folder.- The Maven 3.9 line is the stable release used in this tutorial.
Note: Many projects include the Maven Wrapper (
mvnwandmvnw.cmd). Running./mvnw packagedownloads the exact Maven version the project expects, so nobody needs to install Maven by hand. You can add it to any project withmvn wrapper:wrapper.
The pom.xml File Explained
POM stands for Project Object Model. Every Maven project has a pom.xml in its root folder. This is a complete, minimal one:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gocourse</groupId>
<artifactId>hello-maven</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
| Element | Meaning |
|---|---|
modelVersion | Version of the POM format. Always 4.0.0 for Maven 3. |
groupId | Your organisation or project group, usually a reversed domain such as com.gocourse |
artifactId | The name of this project, used in the JAR file name |
version | The project version. -SNAPSHOT (e.g. 1.0.0-SNAPSHOT) marks a work-in-progress version |
packaging | What to build: jar (default), war or pom |
maven.compiler.release | The Java version to compile for, like javac --release 25 |
project.build.sourceEncoding | The character encoding of your source files |
Add one class in the standard location and compile it:
// src/main/java/com/gocourse/Hello.java
package com.gocourse;
public class Hello {
public static void main(String[] args) {
System.out.println("Hello from Maven!");
}
}
mvn compile
java -cp target/classes com.gocourse.Hello
Output (Maven log shortened; plugin versions may differ):
[INFO] Building hello-maven 1.0.0
[INFO] --- resources:3.3.1:resources (default-resources) @ hello-maven ---
[INFO] --- compiler:3.13.0:compile (default-compile) @ hello-maven ---
[INFO] Compiling 1 source file with javac [debug release 25] to target/classes
[INFO] BUILD SUCCESS
Hello from Maven!
How it works:
- Maven found
Hello.javabecause it lives insrc/main/java, so no source path was configured. - The compiled class went to
target/classes, Maven's output folder. java -cp target/classesruns the class directly. Later you will package it as a JAR instead.
Maven Standard Directory Layout
Every Maven project uses the same folder structure. Once you know it, you can find your way around any Maven project.
hello-maven/
├── pom.xml
├── src/
│ ├── main/
│ │ ├── java/ <- application source code
│ │ └── resources/ <- config files, copied into the JAR
│ └── test/
│ ├── java/ <- test source code
│ └── resources/ <- files used only by tests
└── target/ <- build output, created by Maven (never commit it)
How it works:
- Code in
src/maingoes into the final JAR. Code insrc/testis compiled and run during the build but never packaged. - Files in
src/main/resources, such asapp.properties, are copied totarget/classesand can be loaded from the classpath. mvn cleandeletestarget/, so addtarget/to your.gitignore.
Maven Coordinates: groupId, artifactId and version
The three values groupId:artifactId:version (often written GAV) uniquely identify a project or library. Maven uses them to find libraries in Maven Central, the public repository, and to store them on your computer.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.13.2</version>
</dependency>
After the first build that uses this library, it sits in your local repository:
ls ~/.m2/repository/com/google/code/gson/gson/2.13.2/
Output (shortened):
gson-2.13.2.jar
gson-2.13.2.pom
How it works:
- Dots in the
groupIdbecome folders:com.google.code.gsonturns intocom/google/code/gson. - Maven downloads a library once and reuses it from
~/.m2/repositoryin every project. - Your own project also has coordinates.
mvn installcopies your JAR into the local repository so other local projects can use it.
Adding and managing libraries is covered in detail in Maven Dependencies.
Maven Build Lifecycle and Phases
A lifecycle is an ordered list of phases. Maven has three built-in lifecycles: clean, default (the build) and site (documentation). These are the most important phases of the default lifecycle:
| Phase | What happens |
|---|---|
validate | Checks that the project is correct |
compile | Compiles src/main/java into target/classes |
test | Compiles and runs unit tests from src/test/java |
package | Creates the JAR (or WAR) in target/ |
verify | Runs integration tests and quality checks |
install | Copies the JAR into your local repository ~/.m2/repository |
deploy | Uploads the JAR to a remote repository for other developers |
When you run a phase, Maven runs every phase before it first:
mvn clean package
Output (shortened; plugin versions may differ):
[INFO] --- clean:3.2.0:clean (default-clean) @ hello-maven ---
[INFO] Deleting /home/asha/hello-maven/target
[INFO] --- resources:3.3.1:resources (default-resources) @ hello-maven ---
[INFO] --- compiler:3.13.0:compile (default-compile) @ hello-maven ---
[INFO] --- resources:3.3.1:testResources (default-testResources) @ hello-maven ---
[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ hello-maven ---
[INFO] --- surefire:3.2.5:test (default-test) @ hello-maven ---
[INFO] No tests to run.
[INFO] --- jar:3.4.1:jar (default-jar) @ hello-maven ---
[INFO] Building jar: /home/asha/hello-maven/target/hello-maven-1.0.0.jar
[INFO] BUILD SUCCESS
How it works:
cleanis a phase of thecleanlifecycle, andpackageis a phase of thedefaultlifecycle. You can list several phases in one command.- Asking for
packagealso ran compile, test-compile and test, in that order. You never needmvn compile test package;mvn packageis enough. - The JAR is named
<artifactId>-<version>.jar.
Maven Plugins and Goals
Maven itself does very little. The real work is done by plugins, and each plugin offers one or more goals (tasks). Phases are bound to goals; for jar packaging the defaults are:
| Phase | Plugin goal that runs |
|---|---|
process-resources | resources:resources |
compile | compiler:compile |
test-compile | compiler:testCompile |
test | surefire:test |
package | jar:jar |
install | install:install |
deploy | deploy:deploy |
You can also run a goal directly with plugin-prefix:goal. For example, the Help plugin shows the complete POM Maven really uses, including all defaults:
mvn help:effective-pom -Doutput=effective-pom.xml
Output (shortened):
[INFO] --- help:3.5.1:effective-pom (default-cli) @ hello-maven ---
[INFO] Effective-POM written to: /home/asha/hello-maven/effective-pom.xml
[INFO] BUILD SUCCESS
How it works:
helpis the plugin prefix andeffective-pomis the goal. Running a goal directly does not run any lifecycle phases.- The effective POM shows every inherited default, such as the plugin versions and the
src/main/javasource folder. It is the best tool for answering "where does this setting come from?". - You configure plugins inside
<build><plugins>in your POM, as the real-world example below does for the JAR plugin.
Note: If you do not set plugin versions, Maven uses default versions that depend on your Maven release, so two developers can get different builds. Real projects pin plugin versions, as shown in Create a Maven Project.
Common Maven Commands
| Command | What it does |
|---|---|
mvn compile | Compile application code |
mvn test | Compile and run unit tests |
mvn package | Build the JAR in target/ |
mvn clean package | Delete target/, then build from scratch |
mvn verify | Package and run integration tests and checks |
mvn install | Put the JAR in ~/.m2/repository |
mvn package -DskipTests | Build without running tests |
mvn test -Dtest=GradeCalculatorTest | Run one test class |
mvn -q package | Quiet output: only warnings and errors |
mvn -o package | Offline: use only libraries already downloaded |
mvn -U package | Force a check for updated snapshot dependencies |
mvn -X package | Debug output for troubleshooting |
Run a single test class from the real-world project below:
mvn test -Dtest=GradeCalculatorTest
Output (shortened):
[INFO] Running com.gocourse.grades.GradeCalculatorTest
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
How it works:
-Dsets a property. Surefire reads thetestproperty and runs only the matching class.- Options such as
-q,-oand-Uchange how Maven runs, not what it builds.
Real-World Example: Build and Run a Java App With Maven
This project prints a grade report for a class of students. It has application code, a JUnit test, and a JAR plugin configuration that makes the JAR executable with java -jar.
grade-report/
├── pom.xml
└── src/
├── main/java/com/gocourse/grades/
│ ├── App.java
│ └── GradeCalculator.java
└── test/java/com/gocourse/grades/
└── GradeCalculatorTest.java
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gocourse</groupId>
<artifactId>grade-report</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>6.1.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.6</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.5.0</version>
<configuration>
<archive>
<manifest>
<mainClass>com.gocourse.grades.App</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.gocourse.grades;
public class GradeCalculator {
public String gradeFor(int marks) {
if (marks < 0 || marks > 100) {
throw new IllegalArgumentException("Marks must be between 0 and 100: " + marks);
}
if (marks >= 90) return "A";
if (marks >= 75) return "B";
if (marks >= 60) return "C";
if (marks >= 40) return "D";
return "F";
}
}
package com.gocourse.grades;
import java.util.LinkedHashMap;
import java.util.Map;
public class App {
public static void main(String[] args) {
GradeCalculator calculator = new GradeCalculator();
Map<String, Integer> marksByStudent = new LinkedHashMap<>(); // keeps insertion order
marksByStudent.put("Asha", 92);
marksByStudent.put("Ravi", 78);
marksByStudent.put("Meena", 55);
marksByStudent.put("Karthik", 34);
System.out.println("Grade report");
marksByStudent.forEach((name, marks) ->
System.out.printf("%-8s %3d %s%n", name, marks, calculator.gradeFor(marks)));
}
}
package com.gocourse.grades;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class GradeCalculatorTest {
private final GradeCalculator calculator = new GradeCalculator();
@ParameterizedTest
@CsvSource({"90, A", "75, B", "60, C", "40, D", "39, F"})
void gradeBoundaries(int marks, String expectedGrade) {
assertEquals(expectedGrade, calculator.gradeFor(marks));
}
@Test
void marksAbove100AreRejected() {
assertThrows(IllegalArgumentException.class, () -> calculator.gradeFor(101));
}
}
Build the project and run the JAR:
mvn clean package
java -jar target/grade-report-1.0.0.jar
Output (Maven log shortened):
[INFO] Running com.gocourse.grades.GradeCalculatorTest
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] --- jar:3.5.0:jar (default-jar) @ grade-report ---
[INFO] Building jar: /home/asha/grade-report/target/grade-report-1.0.0.jar
[INFO] BUILD SUCCESS
Grade report
Asha 92 A
Ravi 78 B
Meena 55 D
Karthik 34 F
How it works:
- Coordinates and Java version.
com.gocourse:grade-report:1.0.0names the project, andmaven.compiler.releasecompiles for Java 25. - Test dependency. JUnit is declared with
testscope, so it is used duringmvn testbut is not needed by the final JAR. The BOM supplies its version. - The lifecycle.
mvn clean packagedeleted old output, compiled both classes, compiled and ran 6 tests (5 parameterized cases plus 1 normal test), and created the JAR. If a test had failed, Maven would have stopped before packaging. - Executable JAR. The JAR plugin wrote
Main-Class: com.gocourse.grades.Appinto the JAR's manifest, sojava -jarknows which class to start. - Formatting.
%-8spads each name to 8 characters and%3dright-aligns the marks, which lines up the columns.
The next lesson, Create a Maven Project, shows how to generate this structure automatically, pin plugin versions and split a larger application into modules.