Gradle in Java
Gradle is a build tool that compiles, tests, packages and runs Java projects. Instead of an XML file, Gradle in Java projects describe the build in a short script written in Kotlin or Groovy, and Gradle skips any step whose inputs have not changed, which keeps builds fast.
This lesson installs Gradle, creates a project with gradle init, explains the Gradle Wrapper and every line of build.gradle.kts, runs the most common tasks, and compares the Kotlin and Groovy DSLs. It ends with a grade calculator built and tested with Gradle. If you already know Maven, see Maven in Java for the same ideas in Maven terms.
Gradle vs Maven for Java Projects
Both tools use the same folder layout and download libraries from Maven Central, so a Java developer can switch between them easily.
| Feature | Maven | Gradle |
|---|---|---|
| Build file | pom.xml (XML) | build.gradle.kts (Kotlin) or build.gradle (Groovy) |
| Unit of work | Plugin goals bound to lifecycle phases | Tasks that depend on other tasks |
| Source folders | src/main/java, src/test/java | Same |
| Output folder | target/ | build/ |
| Skips unchanged work | Partly | Yes, task by task (up-to-date checks and build cache) |
| Pinned tool version | Maven Wrapper (mvnw) | Gradle Wrapper (gradlew) |
| Version conflicts | Nearest declaration wins | Highest version wins |
my-app/
├── settings.gradle.kts <- project name, list of subprojects
├── build.gradle.kts <- plugins, dependencies, Java version
├── gradlew / gradlew.bat <- Gradle Wrapper scripts
├── gradle/wrapper/ <- wrapper JAR and properties
└── src/
├── main/java/...
└── test/java/...
How it works:
settings.gradle.ktsis read first. It names the project and, in larger builds, lists the subprojects.build.gradle.ktsdescribes how to build one project. Plugins add tasks such ascompileJava,testandjar.- Gradle writes everything it produces under
build/, which you add to.gitignorejust like Maven'starget/.
Install Gradle and Check the Version
Gradle runs on the JVM, and Gradle 9 needs Java 17 or newer to run. Install it with a package manager such as SDKMAN! (sdk install gradle), Homebrew (brew install gradle) or Scoop (scoop install gradle), or download it from gradle.org.
gradle --version
Output (shortened):
------------------------------------------------------------
Gradle 9.9.0
------------------------------------------------------------
Launcher JVM: 25.0.1 (Eclipse Adoptium 25.0.1+8-LTS)
OS: Linux 6.8.0 amd64
How it works:
Launcher JVMis the Java that runs Gradle itself. It is not necessarily the Java your code is compiled for; that is set by the toolchain shown later.- You only need an installed Gradle to create a project. After that, every developer uses the project's wrapper, so their installed version does not matter.
Note: Gradle 9.9.0 was released in November 2026. Any recent 9.x version works for every example in this lesson.
Create a Gradle Project With gradle init
gradle init generates a ready-to-run project. The options below create a Java application with JUnit tests and the Kotlin DSL, without asking questions.
mkdir greeter && cd greeter
gradle init --type java-application --dsl kotlin --test-framework junit-jupiter \
--package com.gocourse.greeter --project-name greeter --java-version 25 \
--no-split-project --no-incubating
On Windows Command Prompt, write the command on one line without the `` characters.
Output (shortened):
> Task :init
Learn more about Gradle by exploring our Samples at https://docs.gradle.org/9.9.0/samples/sample_building_java_applications.html
BUILD SUCCESSFUL in 4s
1 actionable task: 1 executed
The main generated files:
greeter/
├── settings.gradle.kts
├── gradle/libs.versions.toml <- version catalog
├── gradlew, gradlew.bat, gradle/wrapper/
└── app/
├── build.gradle.kts
└── src/
├── main/java/com/gocourse/greeter/App.java
└── test/java/com/gocourse/greeter/AppTest.java
Run the app through the wrapper:
./gradlew run
Output:
> Task :app:run
Hello World!
BUILD SUCCESSFUL in 3s
2 actionable tasks: 2 executed
How it works:
--type java-applicationapplies theapplicationplugin, which adds theruntask. The code lives in a subproject calledapp, so the task path is:app:run.gradle/libs.versions.tomlis a version catalog: one file that names every library and its version. Gradle Dependencies explains it in detail.- On Windows, run
gradlew run(or.\gradlew runin PowerShell) instead of./gradlew run.
The Gradle Wrapper Explained
The Gradle Wrapper is a small script plus a properties file committed with the project. It downloads the exact Gradle version the project needs, so every developer and CI server builds with the same version.
# gradle/wrapper/gradle-wrapper.properties
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
./gradlew --version
Output (shortened):
Gradle 9.9.0
Add the wrapper to a project that does not have one, or upgrade it:
gradle wrapper --gradle-version 9.9.0
How it works:
- The first
./gradlewcall downloads the distribution fromdistributionUrlinto~/.gradle/wrapper/dists. Later calls reuse it. - Commit
gradlew,gradlew.batand the wholegradle/wrapperfolder. Never commitbuild/or.gradle/. - On Linux and macOS, if you see
Permission denied, make the script executable withchmod +x gradlew.
build.gradle.kts Explained Line by Line
You can also write a Gradle project by hand. This single-project build has no app subfolder, so the files sit next to src/.
// settings.gradle.kts
rootProject.name = "hello-gradle"
// build.gradle.kts
plugins {
application // adds java + run + distribution tasks
}
group = "com.gocourse"
version = "1.0.0"
repositories {
mavenCentral() // where libraries are downloaded from
}
dependencies {
testImplementation(platform("org.junit:junit-bom:6.1.3"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(25) // compile and run with Java 25
}
}
application {
mainClass = "com.gocourse.hello.HelloGradle"
}
tasks.test {
useJUnitPlatform() // run tests with JUnit 6
}
// src/main/java/com/gocourse/hello/HelloGradle.java
package com.gocourse.hello;
public class HelloGradle {
public static void main(String[] args) {
System.out.println("Built by Gradle, running on Java " + Runtime.version().feature());
}
}
gradle wrapper --gradle-version 9.9.0
./gradlew run
Output:
> Task :run
Built by Gradle, running on Java 25
BUILD SUCCESSFUL in 2s
2 actionable tasks: 2 executed
How it works:
| Block | Purpose |
|---|---|
plugins | Applies plugins. application includes the java plugin and adds run |
group, version | Project coordinates, also used in the JAR name |
repositories | Where to look for dependencies |
dependencies | Libraries, each added to a configuration such as implementation |
java.toolchain | The Java version used to compile, test and run |
application.mainClass | The class run starts |
tasks.test | Configures the existing test task |
- The toolchain decouples your code's Java version from the JDK that runs Gradle. Gradle looks for an installed JDK 25 and fails with a clear message if it cannot find one.
- Since Gradle 9, JUnit Platform projects declare
junit-platform-launcherastestRuntimeOnlythemselves; Gradle no longer adds it automatically.
Run Gradle Tasks From the Command Line
A task is one unit of work, such as compiling or running tests. List the tasks a project offers:
./gradlew tasks
Output (shortened):
Application tasks
-----------------
run - Runs this project as a JVM application
Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the main classes.
Verification tasks
------------------
check - Runs all checks.
test - Runs the test suite.
| Command | What it does |
|---|---|
./gradlew build | Compiles, tests and creates the JAR |
./gradlew test | Compiles and runs the tests |
./gradlew run | Runs mainClass |
./gradlew run --args="a b" | Runs it with arguments |
./gradlew clean | Deletes build/ |
./gradlew build -x test | Builds but skips the test task |
./gradlew build --scan | Uploads a detailed build report (asks for permission) |
Run build twice in a row:
./gradlew build
./gradlew build
Output of the second run:
BUILD SUCCESSFUL in 812ms
7 actionable tasks: 7 up-to-date
How it works:
- Gradle records each task's inputs and outputs. If nothing changed, the task is up-to-date and skipped, which is why the second build takes under a second.
-x testexcludes one task. Use it sparingly; tests exist to stop broken code from being packaged.- Gradle keeps a background daemon running after the first build, so later builds start faster. Stop it with
./gradlew --stop.
Kotlin DSL vs Groovy DSL in Gradle
Gradle supports two script languages. New projects default to the Kotlin DSL, but many older projects use Groovy.
| Kotlin DSL | Groovy DSL | |
|---|---|---|
| File names | build.gradle.kts, settings.gradle.kts | build.gradle, settings.gradle |
| Strings | Double quotes only | Single or double quotes |
| Method calls | Always use parentheses | Parentheses optional |
| IDE support | Full code completion and type checking | Weaker completion |
The same build in Groovy:
// build.gradle
plugins {
id 'application'
}
repositories {
mavenCentral()
}
dependencies {
testImplementation platform('org.junit:junit-bom:6.1.3')
testImplementation 'org.junit.jupiter:junit-jupiter'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(25)
}
}
application {
mainClass = 'com.gocourse.hello.HelloGradle'
}
tasks.named('test') {
useJUnitPlatform()
}
How it works:
- Both files produce exactly the same build; only the syntax differs.
- The Kotlin DSL is checked as you type, so a misspelled block name shows an error in the IDE instead of at build time. The rest of this tutorial uses it.
Real-World Example: Gradle in Java for a Grade Calculator
This project turns command-line arguments like Asha:92 into letter grades and a class average. It shows a complete hand-written Gradle build with the toolchain, the application plugin and JUnit tests.
// settings.gradle.kts
rootProject.name = "grade-calculator"
// build.gradle.kts
plugins {
application
}
group = "com.gocourse"
version = "1.0.0"
repositories {
mavenCentral()
}
dependencies {
testImplementation(platform("org.junit:junit-bom:6.1.3"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(25)
}
}
application {
mainClass = "com.gocourse.grades.GradeApp"
}
tasks.test {
useJUnitPlatform()
testLogging {
events("passed", "failed") // print each test result
}
}
// src/main/java/com/gocourse/grades/GradeCalculator.java
package com.gocourse.grades;
import java.util.List;
public class GradeCalculator {
/** Converts marks out of 100 into a letter grade. */
public static char letterFor(int marks) {
if (marks < 0 || marks > 100) {
throw new IllegalArgumentException("Marks must be 0-100, got " + marks);
}
if (marks >= 90) return 'A';
if (marks >= 75) return 'B';
if (marks >= 60) return 'C';
if (marks >= 40) return 'D';
return 'F';
}
public static double average(List<Integer> allMarks) {
return allMarks.stream().mapToInt(Integer::intValue).average().orElse(0);
}
}
// src/main/java/com/gocourse/grades/GradeApp.java
package com.gocourse.grades;
import java.util.ArrayList;
import java.util.List;
public class GradeApp {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: gradlew run --args=\"Name:marks Name:marks\"");
return;
}
List<Integer> allMarks = new ArrayList<>();
for (String entry : args) {
String[] parts = entry.split(":");
String name = parts[0];
int marks = Integer.parseInt(parts[1]);
allMarks.add(marks);
System.out.printf("%-6s %3d %c%n", name, marks, GradeCalculator.letterFor(marks));
}
System.out.printf("Class average: %.1f%n", GradeCalculator.average(allMarks));
}
}
// src/test/java/com/gocourse/grades/GradeCalculatorTest.java
package com.gocourse.grades;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.List;
import org.junit.jupiter.api.Test;
class GradeCalculatorTest {
@Test
void boundaryMarksGetTheHigherGrade() {
assertEquals('A', GradeCalculator.letterFor(90));
assertEquals('B', GradeCalculator.letterFor(75));
assertEquals('F', GradeCalculator.letterFor(39));
}
@Test
void marksOutsideRangeAreRejected() {
assertThrows(IllegalArgumentException.class, () -> GradeCalculator.letterFor(101));
}
@Test
void averageOfThreeStudents() {
assertEquals(75.0, GradeCalculator.average(List.of(92, 78, 55)));
}
}
Build, test and run:
gradle wrapper --gradle-version 9.9.0
./gradlew build
./gradlew run --args="Asha:92 Ravi:78 Meena:55"
Output:
> Task :test
GradeCalculatorTest > boundaryMarksGetTheHigherGrade() PASSED
GradeCalculatorTest > marksOutsideRangeAreRejected() PASSED
GradeCalculatorTest > averageOfThreeStudents() PASSED
BUILD SUCCESSFUL in 5s
7 actionable tasks: 7 executed
> Task :run
Asha 92 A
Ravi 78 B
Meena 55 D
Class average: 75.0
BUILD SUCCESSFUL in 1s
2 actionable tasks: 1 executed, 1 up-to-date
How it works:
- Two small files.
settings.gradle.ktsnames the project andbuild.gradle.ktsholds the whole build. Gradle's conventions supply the source folders, output folders and task order. - Toolchain. Both the compile and the
runtask use Java 25, even if Gradle itself was started with a different JDK. - Tests run in
build.builddepends oncheck, which depends ontest.testLoggingprints each result, and a failure stops the build. The HTML report is inbuild/reports/tests/test/index.html. - Up-to-date checks. In the
runstep,compileJavawas already up-to-date frombuild, so Gradle executed onlyrunitself. - Output files. The JAR is
build/libs/grade-calculator-1.0.0.jar, named fromrootProject.nameandversion.
The next lesson, Gradle Build, looks inside the build: the task graph, custom tasks and multi-project builds. To compare this with the same app built by Maven's plugins, see Maven Plugins.