Tutorials / Java: From Zero to Advanced / Maven and Gradle basics

Maven and Gradle basics

14 min read xml
Course contents (20 lessons)
  1. Getting started
  2. Installing JDK 21 and running Java code
  3. Your first program: how a Java file is built
  4. Language basics
  5. Variables and data types
  6. Strings, formatting and text blocks
  7. Control flow: if, switch expressions and loops
  8. Data and methods
  9. Arrays and the collections framework
  10. Methods, overloading and varargs
  11. Object-oriented Java
  12. Classes, objects and encapsulation
  13. Inheritance, abstract classes and interfaces
  14. Records, enums and sealed types
  15. Writing robust code
  16. Exceptions: checked, unchecked and try-with-resources
  17. Generics, bounded types and wildcards
  18. Files and the NIO.2 API
  19. Modern Java
  20. Lambdas and the Stream API
  21. Optional: handling missing values
  22. Concurrency: executors, CompletableFuture and virtual threads
  23. Tools, services and the final project
  24. Maven and Gradle basics
  25. Testing with JUnit 5
  26. A small REST service with the JDK HTTP server
  27. Final project: a library manager

Why you need a build tool

So far we ran single files. A real project has many source files, libraries written by other people, tests and a packaging step. Typing javac with a long class path by hand does not scale. A build tool does these jobs: it downloads dependencies, compiles, runs the tests and produces a jar file. In the Java world there are two main tools, Maven and Gradle. Both are widely used, and both can do everything this lesson needs. Pick whichever your team uses. If you are free to choose, Maven is simpler to learn, and Gradle is more flexible.

Maven

A Maven project is described by a file called pom.xml (Project Object Model). Maven follows a strict folder layout, so it needs little configuration.

my-app/
  pom.xml
  src/
    main/java/com/example/App.java
    test/java/com/example/AppTest.java

Here is a complete pom.xml for a Java 21 project with JUnit 5 and a runnable jar.

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>my-app</artifactId>
  <version>1.0.0</version>
  <packaging>jar</packaging>

  <properties>
    <maven.compiler.release>21</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <!-- Test dependency: only on the test class path -->
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.11.4</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.5.2</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.4.2</version>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.example.App</mainClass>
            </manifest>
          </archive>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Version numbers change over time. The ones above were current when this lesson was written. Check Maven Central or your IDE for newer ones when you start a project.

Walking through the pom

The three coordinates groupId, artifactId and version identify your project, and every library on Maven Central is identified the same way. A group id is usually a reversed domain name that you control. maven.compiler.release set to 21 tells the compiler to target Java 21 and to allow only the APIs of that version. Prefer release over the older source and target settings.

A dependency is declared by its coordinates. Maven downloads the jar, and the jars it depends on, into a local cache folder, .m2 in your home directory. The test scope means the library is available only when compiling and running tests, and it is not part of the final application. The default scope, compile, includes it everywhere.

Plugins add behaviour to the build. Surefire runs the tests. Pinning its version matters, because old default versions do not detect JUnit 5 properly. The jar plugin writes the Main-Class entry into the jar manifest, so that java -jar knows where to start.

The commands you use every day

mvn compile          # compile main code
mvn test             # compile and run tests
mvn package          # test, then build target/my-app-1.0.0.jar
mvn clean package    # delete target/ first, then package
java -jar target/my-app-1.0.0.jar

Maven works in lifecycle phases. Each phase runs everything before it, so mvn package compiles and tests first. If a test fails, the build stops there. That is a feature. Build output goes into target/, which you should never commit to Git. Add it to .gitignore.

Gradle

Gradle describes the same project in a script, usually written in the Kotlin DSL, build.gradle.kts.

plugins {
    java
    application
}

repositories {
    mavenCentral()
}

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(21)
    }
}

dependencies {
    testImplementation(platform("org.junit:junit-bom:5.11.4"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

application {
    mainClass = "com.example.App"
}

tasks.test {
    useJUnitPlatform()
}

The folder layout is the same. You run ./gradlew build, ./gradlew test and ./gradlew run (gradlew.bat on Windows). The wrapper script, gradlew, downloads the right Gradle version for the project, so nobody needs to install Gradle. Maven has the same idea with mvnw. Use the wrapper in every project, so that your build works the same on every machine. The toolchain setting asks Gradle to find or provision a JDK 21, whichever JDK launched Gradle.

Maven or Gradle

MavenGradle
Config styleDeclarative XMLScript (Kotlin or Groovy)
Learning curveGentler, predictableSteeper, very flexible
SpeedGoodOften faster on large builds, thanks to caching
Typical useEnterprise, many Spring projectsAndroid, large multi-module builds

Common mistakes

  • Putting source files in the wrong folder. Both tools expect src/main/java and src/test/java.
  • Running with an old JDK. A build for release 21 fails with "invalid target release" on JDK 17. Check mvn -version, which shows the JDK it uses.
  • Not pinning the Surefire version. Tests silently do not run.
  • Committing target/ or build/.
  • Copying dependencies from random websites instead of using Maven Central.

Try it yourself

  1. Create the Maven folder layout and a class com.example.App that prints a message. Run mvn package and start the jar.
  2. Add the library org.apache.commons:commons-lang3 as a dependency, using the version shown on Maven Central, and call StringUtils.capitalize from your program.
  3. Write the same project with Gradle and compare the two files.
xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>my-app</artifactId>
  <version>1.0.0</version>
  <packaging>jar</packaging>

  <properties>
    <maven.compiler.release>21</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <!-- Test dependency: only on the test class path -->
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.11.4</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.5.2</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.4.2</version>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.example.App</mainClass>
            </manifest>
          </archive>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account