Maven in Java

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 258 of 306

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.

TaskWithout MavenWith Maven
Compilejavac -d out -cp lib/* src/com/gocourse/*.javamvn compile
Get librariesDownload JARs and their dependencies by handDeclare them in pom.xml; Maven downloads them
Run testsBuild a classpath and start the test runner yourselfmvn test
Create a JARjar --create --file app.jar --main-class ...mvn package
Same build for the whole teamShared notes and scriptsOne 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 -v prints the Maven version and the JDK Maven will use. If the Java version is wrong, set the JAVA_HOME environment 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 (mvnw and mvnw.cmd). Running ./mvnw package downloads the exact Maven version the project expects, so nobody needs to install Maven by hand. You can add it to any project with mvn 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>
ElementMeaning
modelVersionVersion of the POM format. Always 4.0.0 for Maven 3.
groupIdYour organisation or project group, usually a reversed domain such as com.gocourse
artifactIdThe name of this project, used in the JAR file name
versionThe project version. -SNAPSHOT (e.g. 1.0.0-SNAPSHOT) marks a work-in-progress version
packagingWhat to build: jar (default), war or pom
maven.compiler.releaseThe Java version to compile for, like javac --release 25
project.build.sourceEncodingThe 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.java because it lives in src/main/java, so no source path was configured.
  • The compiled class went to target/classes, Maven's output folder.
  • java -cp target/classes runs 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/main goes into the final JAR. Code in src/test is compiled and run during the build but never packaged.
  • Files in src/main/resources, such as app.properties, are copied to target/classes and can be loaded from the classpath.
  • mvn clean deletes target/, so add target/ 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 groupId become folders: com.google.code.gson turns into com/google/code/gson.
  • Maven downloads a library once and reuses it from ~/.m2/repository in every project.
  • Your own project also has coordinates. mvn install copies 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:

PhaseWhat happens
validateChecks that the project is correct
compileCompiles src/main/java into target/classes
testCompiles and runs unit tests from src/test/java
packageCreates the JAR (or WAR) in target/
verifyRuns integration tests and quality checks
installCopies the JAR into your local repository ~/.m2/repository
deployUploads 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:

  • clean is a phase of the clean lifecycle, and package is a phase of the default lifecycle. You can list several phases in one command.
  • Asking for package also ran compile, test-compile and test, in that order. You never need mvn compile test package; mvn package is 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:

PhasePlugin goal that runs
process-resourcesresources:resources
compilecompiler:compile
test-compilecompiler:testCompile
testsurefire:test
packagejar:jar
installinstall:install
deploydeploy: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:

  • help is the plugin prefix and effective-pom is 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/java source 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

CommandWhat it does
mvn compileCompile application code
mvn testCompile and run unit tests
mvn packageBuild the JAR in target/
mvn clean packageDelete target/, then build from scratch
mvn verifyPackage and run integration tests and checks
mvn installPut the JAR in ~/.m2/repository
mvn package -DskipTestsBuild without running tests
mvn test -Dtest=GradeCalculatorTestRun one test class
mvn -q packageQuiet output: only warnings and errors
mvn -o packageOffline: use only libraries already downloaded
mvn -U packageForce a check for updated snapshot dependencies
mvn -X packageDebug 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:

  • -D sets a property. Surefire reads the test property and runs only the matching class.
  • Options such as -q, -o and -U change 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:

  1. Coordinates and Java version. com.gocourse:grade-report:1.0.0 names the project, and maven.compiler.release compiles for Java 25.
  2. Test dependency. JUnit is declared with test scope, so it is used during mvn test but is not needed by the final JAR. The BOM supplies its version.
  3. The lifecycle. mvn clean package deleted 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.
  4. Executable JAR. The JAR plugin wrote Main-Class: com.gocourse.grades.App into the JAR's manifest, so java -jar knows which class to start.
  5. Formatting. %-8s pads each name to 8 characters and %3d right-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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Maven in Java and get answers drawn from it.

Signed-in readers only.