Maven/Gradle
Dependencies
Learn how to add external libraries to your Java project using build tools, so you never have to manage .jar files by hand again.
What Is a Dependency?
A dependency is an external library or module your project needs to compile and run. Instead of copying code, you declare what you need, and the build tool downloads it for you.
Meet Maven and Gradle
Both are build tools for Java. They automate compiling, testing, packaging, and managing dependencies. The main difference is how you write their config files.
How Dependencies Flow
The GAV Coordinate System
Every dependency on Maven Central is uniquely identified by three coordinates. Think of it as a mailing address for code:
Maven: pom.xml Syntax
In Maven, you declare dependencies inside a <dependencies> block in your pom.xml file using XML tags:
Gradle: build.gradle Syntax
In Gradle, the same dependency is a single concise line inside a dependencies block. The GAV is separated by colons:
Maven vs Gradle: Side by Side
| Feature | Maven | Gradle |
|---|---|---|
| Config file | pom.xml | build.gradle |
| Language | XML | Groovy / Kotlin |
| Dependency format | 6 lines of XML tags | 1 line: 'G:A:V' |
| Build command | mvn compile | gradle build |
| Local cache | ~/.m2/repository | ~/.gradle/caches |
| Popularity | Enterprise / legacy | Android / modern |
Understanding Scopes
A scope (Maven) or configuration (Gradle) controls when a dependency is available: at compile time, runtime, or only for tests.
How to Add a Dependency
Example: Adding Gson in Maven
Goal: parse JSON strings in your Java app using Google's Gson library.
Example: Adding JUnit 5 in Gradle
Goal: set up unit testing in a Gradle project. JUnit is a test-only dependency, so we use testImplementation.
Example: Multiple Dependencies
Real projects often need several libraries. Just stack them in the same block:
Transitive Dependencies
When you add library A, it might depend on library B, which depends on C. The build tool fetches all of them automatically: these are called transitive dependencies.
Common Mistakes
Question 1 of 5
What are the three parts of a Maven/Gradle dependency coordinate (the "GAV")?
Question 2 of 5
In a Gradle build file, which keyword adds a dependency that is only available during testing?
Question 3 of 5
You added a dependency to your pom.xml, but your IDE says the class cannot be found. What is the most likely fix?
Question 4 of 5
Which of the following is the correct Gradle syntax to add version 3.14.0 of Apache Commons Lang?
Question 5 of 5
What are transitive dependencies?