Java • Getting Started and Tooling

Maven/Gradle Dependencies — Add a dependency and build a project using Maven/Gradle (intro workflow)

Learn how build tools automatically manage libraries so you can focus on writing great Java code.

Java programming emblem with a coffee cup, code braces, and terminal
Inside this lesson 10 sections 5 questions 4 figures

SECTION 1

Historical Context & Motivation

In the early days of Java development, programmers had to manually download every library their project needed. Imagine you are building a web application that needs to read JSON data, connect to a database, and run unit tests. You would have to visit three different websites, download three separate JAR files (Java Archive files, which are packaged collections of compiled Java code), place them in the right folder, and tell the compiler exactly where to find them. If any of those libraries depended on other libraries, you had to track those down too. This tedious process was error-prone, time-consuming, and nearly impossible to manage in large projects.

The Java community needed a tool that could automatically fetch libraries, resolve their sub-dependencies, compile code, run tests, and package applications — all with a single command. This need gave rise to build tools like Apache Maven and Gradle, which became the standard way to manage Java projects.

2000 • Apache Ant Released

Ant was the first major Java build tool. It automated compilation and packaging, but developers still managed library downloads manually.

2004 • Apache Maven 1.0

Maven introduced the concept of a central repository and automatic dependency resolution. Developers could declare what they needed, and Maven would fetch it.

2005 • Maven Central Repository

The Maven Central Repository became the world's largest public collection of Java libraries, hosting hundreds of thousands of packages available to any developer.

2012 • Gradle 1.0

Gradle combined Maven's dependency management with a more flexible, code-based build script. It used Groovy (and later Kotlin) instead of XML, making builds easier to customize.

2020s • Industry Standard

Today, nearly every professional Java project uses either Maven or Gradle. Android development adopted Gradle as its official build system, further cementing its popularity.

The central question these tools answer is straightforward: How can we reliably manage the external code our project depends on and automate the entire build process? Understanding Maven and Gradle is essential because almost every Java job or open-source project you encounter will use one of these tools.

SECTION 2

Core Principles & Definitions

Before you start using Maven or Gradle, you need to understand a handful of key ideas that both tools share. These concepts form the foundation of modern Java project management.

1

Dependency

An external library (packaged as a JAR) that your project needs to compile or run. For example, the gson library lets you convert Java objects to JSON.
2

Repository

A remote server that stores thousands of libraries. Maven Central is the default repository. When you declare a dependency, the build tool downloads it from a repository automatically.
3

Build Lifecycle

A defined sequence of phases — such as compile, test, and package — that transforms your source code into a runnable application. You execute these phases with a single terminal command.
4

Build File

The configuration file that describes your project. Maven uses pom.xml (Project Object Model) and Gradle uses build.gradle. Both list your dependencies and build settings.
5

GAV Coordinates

Every library is identified by three values: Group ID (organization), Artifact ID (library name), and Version. Together these uniquely locate any library.
✦

KEY TAKEAWAY

Think of a build tool like a recipe app for cooking. The build file is your recipe, dependencies are the ingredients you need, and the repository is the grocery store. Instead of driving to the store yourself, the build tool reads your recipe and delivers all the ingredients to your kitchen automatically. You just write the recipe once, and everything else is handled for you.

SECTION 3

Visual Explanation — How Build Tools Work

The diagram below shows the complete workflow when you run a build command. Your build file declares what your project needs, the build tool fetches dependencies from a remote repository, stores them in a local cache on your machine, and then compiles, tests, and packages your code into a final JAR or application.

Build Tool Workflow — From Source to ExecutableYour Source Codesrc/main/java/*.javaBuild Filepom.xml / build.gradleBUILD TOOLMaven or GradleReads build file → orchestratesMaven Central RepoRemote — 500k+ librariesrepo1.maven.orgLocal Cache~/.m2/repositoryfetchcacheprovide JARs① Compile.java → .class② Testrun unit tests③ Packagecreate .jar file✓ Final Outputmy-app-1.0.jar (ready to run!)
The build tool reads your build file, fetches dependencies from Maven Central, caches them locally, then runs the compile → test → package lifecycle to produce a runnable JAR.

Notice that once a library is downloaded from Maven Central, it is stored in your local cache. The next time you build, the tool checks the cache first, which means it does not need to re-download anything unless the version changes. This makes subsequent builds much faster.

SECTION 4

How It Works — Build File Anatomy

Both Maven and Gradle use a configuration file that lives in the root directory of your project. This file tells the build tool three critical things: what your project is called, what dependencies it needs, and how to build it. Let's look at each tool's syntax side by side.

Maven — pom.xml

Maven uses an XML file called pom.xml (Project Object Model). Every Maven project must have this file in its root folder. A minimal pom.xml that adds the Gson JSON library looks like this:

ℹ

Maven pom.xml Example

<project> <modelVersion>4.0.0</modelVersion> <groupId>com.myschool</groupId> <artifactId>my-app</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> </dependency> </dependencies> </project>

The <groupId>, <artifactId>, and <version> inside the <dependency> block are the GAV coordinates that uniquely identify the Gson library. Maven uses these to look up the exact JAR on Maven Central.

Gradle — build.gradle

Gradle uses a file written in Groovy (or Kotlin) that is shorter and more readable. The same dependency declaration in Gradle's build.gradle file looks like this:

ℹ

Gradle build.gradle Example

plugins { id 'java' } repositories { mavenCentral() } dependencies { implementation 'com.google.code.gson:gson:2.10.1' }

Notice that Gradle compresses the GAV coordinates into a single colon-separated string: groupId:artifactId:version. The keyword implementation means this dependency is needed at compile time and runtime. Gradle also requires you to explicitly declare which repository to use — mavenCentral() points to the same central repository Maven uses by default.

✦

KEY TAKEAWAY

Both tools do the same core job — they just use different file formats. Maven's pom.xml is like filling out a structured form, while Gradle's build.gradle is like writing a short script. Either way, you declare what you need, and the tool figures out how to get it.

SECTION 5

Standard Project Structure

Both Maven and Gradle expect your files to follow a standard directory layout. This convention means every Java project looks the same, which makes it easier to jump into someone else's code. The diagram below shows the folder structure for a typical project.

Standard Maven / Gradle Project Directory📁 my-app/📄 pom.xml(Maven)📄 build.gradle(Gradle)📁 src/📁 main/java/App.java← your code📁 test/java/AppTest.java← tests📁 target/(build output)Key Folders Explainedsrc/main/javaYour application source codegoes here.src/test/javaAutomated tests that verifyyour code works correctly.target / buildCompiled .class files and thefinal packaged JAR appear here.pom.xml (Maven)XML config listing projectinfo and dependencies.build.gradle (Gradle)Groovy/Kotlin script forproject config and deps.
Both Maven and Gradle share the same standard directory layout. Your code goes in src/main/java, tests go in src/test/java, and build output lands in target (Maven) or build (Gradle).

Following this convention is important because both build tools automatically know where to look for source files, test files, and resources. If you place files in the wrong folder, the build tool will not find them and your project will not compile.

SECTION 6

Worked Example — Creating a Maven Project from Scratch

Let's walk through creating a complete Maven project that uses the Gson library to convert a Java object into a JSON string. We will use only the command line and a text editor.

Build a Maven Project with a Gson Dependency

  1. 1

    Step 1 — Generate the project skeleton

    Open a terminal and run the Maven archetype command to create a new project: mvn archetype:generate -DgroupId=com.myschool -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false. This creates a folder called my-app with the standard directory structure and a starter pom.xml.
    A my-app/ directory is created with pom.xml and src/ folders.
  2. 2

    Step 2 — Add the Gson dependency to pom.xml

    Open pom.xml in a text editor and add a <dependencies> section. Inside it, add: <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> </dependency>. You can find these coordinates by searching on search.maven.org.
    The Gson dependency is now declared. Maven will download it on the next build.
  3. 3

    Step 3 — Write Java code that uses Gson

    Open src/main/java/com/myschool/App.java and replace its contents with: package com.myschool; import com.google.gson.Gson; public class App { public static void main(String[] args) { Gson gson = new Gson(); String json = gson.toJson(new int[]{1, 2, 3}); System.out.println(json); } }. This code imports Gson, creates an array, and prints it as JSON.
    App.java now depends on the Gson library.
  4. 4

    Step 4 — Build the project

    In the terminal, navigate into the my-app folder and run: mvn package. Maven will download Gson from Maven Central, compile your code, run any tests, and package everything into a JAR file located at target/my-app-1.0.jar.
    BUILD SUCCESS — the project compiles and packages successfully.
  5. 5

    Step 5 — Run the application

    Execute the application with: java -cp target/my-app-1.0.jar com.myschool.App. You should see [1,2,3] printed to the console. The Gson library successfully converted the Java array into a JSON string.
    Output: [1,2,3] — the project is working!

SECTION 7

Maven vs. Gradle — Strengths & Limitations

Both Maven and Gradle are excellent tools, and the best choice often depends on your project or team's preferences. The table below compares them across several important dimensions so you can make an informed decision.

FeatureMavenGradle
Config LanguageXML (pom.xml) — verbose but very structuredGroovy or Kotlin (build.gradle) — concise and scriptable
Learning CurveEasier for beginners; rigid conventions guide youSlightly steeper; more flexibility means more choices
Build SpeedRebuilds everything each time by defaultIncremental builds and caching — significantly faster
CustomizationLimited without writing pluginsHighly customizable with build scripts
Industry UseDominant in enterprise Java and legacy projectsDefault for Android; growing rapidly in all Java
Dependency MgmtAutomatic via Maven CentralAutomatic via Maven Central (or other repos)

Comparison of Maven and Gradle across key features

✦

KEY TAKEAWAY

Think of Maven and Gradle like two different GPS apps for your phone. Both will get you to the same destination — a successfully built Java project. Maven is like the built-in maps app: reliable, simple, and no surprises. Gradle is like a feature-rich third-party app: faster routing, more options, but a few more buttons to learn. Pick whichever one your project or class uses, and you will be in great shape.

SECTION 8

Connection to Advanced Concepts

The introductory workflow you have learned — declaring a dependency and running a build — is just the tip of the iceberg. As your projects grow, you will encounter more sophisticated features of Maven and Gradle. The table below previews what lies ahead as you continue your Java journey.

What You Know NowWhat Comes Next
Adding a single dependencyTransitive dependencies — libraries that your dependencies themselves need, managed automatically
Running mvn packageMulti-module projects — splitting a large application into multiple sub-projects that build together
Using Maven CentralPrivate repositories — companies host their own internal libraries on servers like Nexus or Artifactory
Manual terminal commandsCI/CD pipelines — automated systems like GitHub Actions that build, test, and deploy your code on every commit
Single implementation scopeDependency scopes — controlling whether a library is available only at compile time, test time, or runtime

From introductory to advanced build tool concepts

Do not worry about mastering all of these right now. The fundamental skill — writing a build file, declaring dependencies, and running a build — is the foundation that everything else builds on. Once you are comfortable with the basics, each advanced concept is just a small addition to what you already know.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain what a dependency is in the context of a Java project. Why would you use a build tool to manage dependencies instead of downloading JAR files manually?
Show answer
A dependency is an external library that your project needs in order to compile or run. For example, if you want to parse JSON data, you might depend on the Gson library. A build tool like Maven or Gradle manages dependencies because it automatically downloads the correct version of every library you need, including libraries that those libraries depend on (called transitive dependencies). Manual management becomes impractical as projects grow, since a real application may need dozens of libraries that each have their own sub-dependencies.

Question 2: BASIC CALCULATION

Write the XML snippet you would add to a Maven pom.xml file to declare a dependency on the JUnit 5 testing library. The GAV coordinates are: groupId = org.junit.jupiter, artifactId = junit-jupiter, version = 5.10.0.
Show answer
You would add the following inside the <dependencies> section of your pom.xml: <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>5.10.0</version> </dependency>. The groupId identifies the organization (JUnit), the artifactId is the specific library name, and the version tells Maven exactly which release to download. After saving the file and running mvn package, Maven will fetch JUnit 5 and make it available in your project.

Question 3: INTERMEDIATE

You have a Gradle project and want to add both the Gson library (com.google.code.gson:gson:2.10.1) and the Apache Commons Lang library (org.apache.commons:commons-lang3:3.14.0). Write the complete dependencies block for build.gradle. Then explain what would happen if you forgot to include the repositories { mavenCentral() } block.
Show answer
The dependencies block would be: dependencies { implementation 'com.google.code.gson:gson:2.10.1' implementation 'org.apache.commons:commons-lang3:3.14.0' }. Each line uses the colon-separated format groupId:artifactId:version. If you omit the repositories { mavenCentral() } block, Gradle would not know where to look for the libraries. The build would fail with an error saying it could not resolve the dependencies, because Gradle — unlike Maven — does not assume a default repository.

Question 4: APPLIED

Your teammate sends you a Java project on GitHub. When you clone it and try to compile, the terminal shows the error: package org.json does not exist. The project uses Maven. Describe the most likely cause of this error and the steps you would take to fix it.
Show answer
The most likely cause is that the project's pom.xml is missing a dependency declaration for the org.json library, or you tried to compile with javac directly instead of using Maven. To fix it, first check the pom.xml for a dependency with artifactId json. If it is missing, search Maven Central for the correct GAV coordinates (groupId: org.json, artifactId: json), add the dependency to pom.xml, and then run mvn package. Maven will download the library and the error should be resolved.

Question 5: CRITICAL THINKING

Imagine you are choosing between Maven and Gradle for a brand-new school project. Your team has three members, two of whom have never used a build tool before. The project is a small command-line app that will use two external libraries. Which tool would you recommend, and why? Consider at least three factors in your reasoning.
Show answer
For this scenario, Maven is likely the better choice for three reasons. First, learning curve: Maven's rigid XML structure and convention-over-configuration approach means beginners have fewer decisions to make. Second, documentation: Maven has been around since 2004, so there are more beginner-friendly tutorials and Stack Overflow answers. Third, project size: Gradle's speed advantages with incremental builds matter most in large projects. For a small app with two libraries, Maven's slower full-rebuild is negligible. However, if the team plans to do Android development next, learning Gradle first would provide a head start, since Android Studio uses Gradle exclusively. A thoughtful answer considers the team's experience, the project scope, and future goals.

SUMMARY

Summary

Summary

Maven and Gradle are build tools that automate the process of managing external libraries and compiling Java projects. Instead of manually downloading JAR files, you declare dependencies using GAV coordinates (Group ID, Artifact ID, Version) in a build file — either pom.xml for Maven or build.gradle for Gradle. The tool downloads the library from a repository like Maven Central and caches it locally.

The standard workflow is straightforward: create a project with the standard directory layout, add dependencies to your build file, write your Java code in src/main/java, and run a single command like mvn package or gradle build to compile, test, and package your application. Mastering this introductory workflow gives you the foundation for every professional Java project you will encounter.

Varsity Tutors • Java • Maven/Gradle Dependencies — Add a dependency and build a project using Maven/Gradle (intro workflow)