Skip to content
Tutorials Center
My learning

Topics

Lesson 162 of 201 ยท JVM and Advanced Topics

Build Tools: Maven and Gradle

Learn why Java projects use build tools, the standard project layout, dependencies, pom.xml and build.gradle.kts basics, and how JAR files and the classpath work.

So far every program in this course has been a single .java file that you run with one click. Real projects are different. They have hundreds of source files in many packages, they use libraries written by other people (and those libraries use more libraries), they have tests that must pass before anything ships, and they end up packaged as a file that a server or a colleague can run. Doing all of that by hand with javac and jar is possible, but it's slow, error-prone and different on every machine.

A build tool automates the whole job: it downloads the libraries you need, compiles your code, runs your tests and packages the result, the same way on every laptop and every build server. The Java world has two big ones: Maven and Gradle. This lesson explains what problem they solve, shows the standard project layout, the files that describe a project (pom.xml and build.gradle.kts), and the JAR files and classpath that sit underneath everything. The Advanced Java track goes much deeper in Maven in Depth and Gradle in Depth.

Building by hand: what a build tool replaces

Before you use a tool, it helps to see the steps it hides. A tiny application with one class goes through three stages:

Terminal
# 1. Compile: .java source -> .class bytecode, into an output folder
javac -d target/classes src/main/java/com/example/app/App.java

# 2. Package: zip the classes into a JAR with a manifest naming the main class
jar --create --file target/app.jar --main-class com.example.app.App -C target/classes .

# 3. Run the JAR
java -jar target/app.jar

You can run those exact steps right here. The JDK exposes javac and jar as Java objects through java.util.spi.ToolProvider, so a program can call them like the command line does, and then start a new JVM with java -jar:

Java Compile, package and run a JAR by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

That works for one class with no libraries. Now imagine the real thing:

  • Dependencies. Your project needs a JSON library, a database driver and a testing framework. Someone has to download the right versions, plus everything those libraries need, and put them all on the classpath for every javac and java call.
  • Tests. Test code must be compiled separately (it shouldn't ship), run after every change, and fail the build if anything breaks.
  • Repeatability. A new team member or a build server must produce exactly the same JAR with one command, without a wiki page of steps.
  • Speed. With thousands of files, only the parts that changed should be recompiled.

Build tools solve all four. You describe the project (its name, Java version and dependencies) and the tool knows how to build it.

The standard project layout

Both Maven and Gradle use the same folder conventions, so any Java developer can open any project and know where things are. Follow them and you need almost no configuration:

TEXT
shop-service/
โ”œโ”€โ”€ pom.xml                  (Maven)  or  build.gradle.kts + settings.gradle.kts (Gradle)
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ main/
โ”‚   โ”‚   โ”œโ”€โ”€ java/            your application code, in package folders
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ com/example/shop/App.java
โ”‚   โ”‚   โ””โ”€โ”€ resources/       non-code files copied into the JAR (config, templates)
โ”‚   โ””โ”€โ”€ test/
โ”‚       โ”œโ”€โ”€ java/            test code (JUnit), never shipped
โ”‚       โ”‚   โ””โ”€โ”€ com/example/shop/AppTest.java
โ”‚       โ””โ”€โ”€ resources/       test-only files
โ””โ”€โ”€ target/   (Maven)  or  build/   (Gradle)   generated output; never commit it

The folder path under src/main/java mirrors the package name: the class com.example.shop.App lives in com/example/shop/App.java. Output goes to target/ (Maven) or build/ (Gradle), which you add to .gitignore. The development environment lesson shows the layout in a full project.

Dependencies and coordinates

A dependency is a library your code uses. Every published Java library is identified by three coordinates, written groupId:artifactId:version:

Part Meaning Example
groupId the organization or project family, usually a reversed domain com.fasterxml.jackson.core
artifactId the library's name jackson-databind
version the exact release 2.22.3

Libraries are published to Maven Central, the huge public repository that both Maven and Gradle use. When you declare a dependency, the tool downloads its JAR into a local cache (~/.m2/repository for Maven, ~/.gradle/caches for Gradle) so later builds work offline.

The killer feature is transitive dependencies. Each library ships a small description of what it needs. When you ask for jackson-databind, the tool reads that description and also fetches jackson-core and jackson-annotations. You declare one line and get a correct set of three JARs. When two libraries need different versions of the same thing, the tool picks one with a fixed rule: Maven takes the version declared nearest to your project in the dependency tree, Gradle takes the highest requested version.

Version numbers themselves need care: they are not plain strings. Sorted alphabetically, 2.10.0 comes before 2.9.1, which is wrong. Build tools compare versions part by part, numerically. The JDK has a parser that follows the same idea:

Java Comparing version numbers correctly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that 2.10.0-rc1 (a release candidate) sorts before 2.10.0: a pre-release is older than the final release. Maven and Gradle have their own, slightly richer rules (they know words like SNAPSHOT, alpha and beta), but the principle is the same.

Dependencies also have a scope: some are needed to compile, some only at runtime (a database driver), some only for tests (JUnit). Tests use test scope in Maven and testImplementation in Gradle, so JUnit never ends up in your shipped application.

Maven: pom.xml

Maven describes a project in an XML file called pom.xml (Project Object Model). Here is a complete, realistic one for a small Java 25 application that uses Jackson and is tested with JUnit:

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

  <groupId>com.example</groupId>
  <artifactId>shop-service</artifactId>
  <version>1.0.0-SNAPSHOT</version>

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

  <dependencies>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.22.3</version>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>6.1.3</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

The project's own coordinates come first, then the Java version (maven.compiler.release), then the dependencies. There are no build steps: Maven has a fixed lifecycle of phases (validate, compile, test, package, verify, install, deploy), and asking for a phase runs every phase before it:

Terminal
mvn compile          # compile src/main/java into target/classes
mvn test             # compile, then compile and run the tests
mvn package          # ...then build target/shop-service-1.0.0-SNAPSHOT.jar
mvn clean package    # delete target/ first, then build from scratch
mvn install          # ...also copy the JAR into ~/.m2 for your other projects

Gradle: build.gradle.kts

Gradle describes the same project with a script, usually written in Kotlin (build.gradle.kts):

Kotlin
plugins {
    application
}

group = "com.example"
version = "1.0.0-SNAPSHOT"

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

repositories {
    mavenCentral()
}

dependencies {
    implementation("com.fasterxml.jackson.core:jackson-databind:2.22.3")
    testImplementation("org.junit.jupiter:junit-jupiter:6.1.3")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

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

tasks.test {
    useJUnitPlatform()
}

A one-line settings.gradle.kts (rootProject.name = "shop-service") names the project. Gradle works with tasks rather than phases, and it skips tasks whose inputs haven't changed, which makes repeated builds fast:

Terminal
./gradlew build      # compile, test and package into build/libs/
./gradlew test       # run the tests
./gradlew run        # run the app (from the application plugin)
./gradlew clean      # delete build/

The wrapper: never install the tool by hand

Notice ./gradlew instead of gradle. Both tools have a wrapper: a small script (gradlew/gradlew.bat, or mvnw/mvnw.cmd for Maven) committed to the project. The first time you run it, it downloads the exact tool version the project needs. Everyone, including the build server, uses the same version, and a newcomer needs only a JDK. Use the wrapper whenever a project has one.

Maven or Gradle?

Maven Gradle
Build file pom.xml (declarative XML) build.gradle.kts (Kotlin script)
Model fixed lifecycle of phases graph of tasks
Strength predictable, every project looks alike fast incremental builds, very flexible
Common in enterprise and Spring projects, libraries Android, large multi-project builds
Conflict rule nearest declaration wins highest version wins

Both use the same layout, coordinates and Maven Central, so the skills transfer. Learn to read both; use whichever your team already uses. Spring's project generator (Spring Boot Introduction) offers both.

JAR files, manifests and the classpath

A JAR (Java ARchive) is a ZIP file containing compiled .class files, resources, and a special file META-INF/MANIFEST.MF with metadata. It's what Maven's package phase and Gradle's jar task produce, and it's how libraries are distributed. Because it's a ZIP, Java can open it with java.util.jar.JarFile. Our runner has Jackson on its classpath, so let's look inside one of its JARs:

Java Looking inside a real library JAR

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The JAR was built by Maven (see Created-By), and Maven stored a copy of the library's own pom.xml inside it. That embedded POM is how build tools learn a library's transitive dependencies. "Multi-Release" means the JAR contains extra versions of some classes under META-INF/versions/, used only on newer Java versions.

Running JARs

There are two ways to run code that lives in JARs:

Terminal
# The JAR's manifest names the main class (Main-Class: com.example.shop.App)
java -jar target/shop-service-1.0.0-SNAPSHOT.jar

# Or list every JAR and folder on the classpath and name the main class yourself
java -cp "target/classes:lib/jackson-databind-2.22.3.jar:lib/jackson-core-2.22.3.jar" com.example.shop.App

On Windows, the classpath separator is ; instead of :. The classpath is the list of places the JVM searches for classes. If a class your code needs isn't on it, the program still starts, and then fails the moment it touches that class:

Java What happens when a dependency is missing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first run prints "App started" and then crashes with NoClassDefFoundError: Greeter: the code compiled fine, but at runtime the JVM couldn't find the class. Assembling the right classpath for compiling, testing and running is exactly the bookkeeping that Maven and Gradle do for you.

Fat JARs

The jar command line

You can also manage JARs without a build tool. The classic short options still work: jar cf app.jar -C classes . creates a JAR, jar tf app.jar lists it, jar uf app.jar -C dir file.txt adds or replaces a file, jar xf app.jar extracts it, jar cfe app.jar com.example.App -C classes . sets the entry point (e), and java -jar app.jar runs it. The long forms (--create, --list, --update, --extract, --main-class, --file) do the same. The older pack200 tool, which compressed JARs further, was removed in Java 14.

Java Create, list, update and extract a JAR

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Fat JARs

A normal JAR contains only your own classes, so java -jar needs the dependencies on the side. For a single-file deployment, build a fat JAR (also called an uber JAR) that bundles your code and every dependency: the Maven Shade plugin or the Gradle Shadow plugin does this, and Spring Boot's build plugins produce a runnable fat JAR automatically. Containers (Docker) and custom runtimes made with jlink (Modules) are the other common ways to ship Java applications.

Use your IDE's build tool integration. IntelliJ IDEA, Eclipse and VS Code all import pom.xml and build.gradle.kts directly. Edit the build file, reload the project, and the IDE downloads the new dependencies and sets up the classpath. You rarely type javac by hand once a project has a build file.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Your project declares only jackson-databind, yet jackson-core also ends up on the classpath. Why?

    Libraries publish their own dependency list (a POM). The build tool reads it and downloads those transitive dependencies, so one declaration brings in a consistent set of JARs.
  2. 2. Where does the class com.example.shop.OrderService belong in a standard Maven or Gradle project?

    Application code lives in src/main/java, in folders that mirror the package name. Resources hold non-code files, and tests go in src/test/java.
  3. 3. A program compiles, starts, prints its first line and then fails with NoClassDefFoundError. What is the most likely cause?

    The JVM loads classes lazily, the first time they're used. If a dependency was on the classpath at compile time but not at runtime, the program starts normally and fails when it first touches the missing class.
  4. 4. Sorted correctly as versions, which comes last in 2.9.1, 2.10.0-rc1, 2.10.0, 2.2.0?

    Versions compare numerically part by part, so 2.10 is newer than 2.9, and a pre-release such as rc1 is older than the final 2.10.0 release.
  5. 5. Why do projects commit mvnw or gradlew scripts?

    The wrapper pins the tool version and downloads it on first use. Newcomers and build servers only need a JDK, and nobody builds with a different tool version by accident.

Summary

  • A build tool downloads dependencies, compiles, runs tests and packages your project with one repeatable command. Maven and Gradle are the two standards.
  • Both use the same layout: src/main/java, src/main/resources, src/test/java, with output in target/ (Maven) or build/ (Gradle).
  • Libraries are identified by groupId:artifactId:version and come from Maven Central; transitive dependencies are fetched automatically, and conflicts are resolved by a fixed rule (Maven: nearest, Gradle: highest).
  • Maven describes a project in pom.xml and builds through lifecycle phases (mvn package); Gradle uses build.gradle.kts and tasks (./gradlew build). Always use the project's wrapper.
  • A JAR is a ZIP of classes and resources with a META-INF/MANIFEST.MF; java -jar needs a Main-Class entry, and every needed JAR must be on the classpath, or you get NoClassDefFoundError at runtime.
  • For depth, continue with Maven in Depth and Gradle in Depth.

Next: Logging, where you'll replace println debugging with real log levels, handlers and formatters.