Sub topic 9
Your First Gradle Project and build.gradle.kts
Gradle is a build tool, like Maven. It compiles your code, runs your tests, and packages your app. Maven reads an XML file. Gradle reads a build script instead. A build script is a small program that describes your build. In this chapter you write one in the Kotlin DSL. A DSL (domain-specific language) is a small language made for one job. Here, that job is describing builds.
The files in a Gradle project
A Gradle project uses the same folder layout as Maven. It adds two files at the top level:
settings.gradle.ktsnames the project.build.gradle.ktssays how to build it.
Step 1: Name the project
Create settings.gradle.kts with one line:
rootProject.name = "hello"Step 2: Write the build script
Create build.gradle.kts:
plugins {
application
}
repositories {
mavenCentral()
}
dependencies {
implementation("com.google.guava:guava:33.2.1-jre")
testImplementation("org.junit.jupiter:junit-jupiter:5.10.2")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
application {
mainClass = "com.example.App"
}
tasks.named<Test>("test") {
useJUnitPlatform()
}Here is what each block does:
| Block | What it does |
|---|---|
| `plugins` | Adds the `application` plugin, which knows how to build and run a Java app |
| `repositories` | Tells Gradle to download libraries from Maven Central |
| `dependencies` | Lists the libraries your code and tests need |
| `java { toolchain }` | Builds with Java 17, even if a different JDK is on your PATH |
| `application` | Names the class that holds `main` |
| `tasks.named<Test>` | Runs tests with JUnit 5 |
Dependency strings use the same group:artifact:version coordinates as Maven. A later chapter explains implementation and the other words in front of them.
Step 3: Add the code
Put this class at src/main/java/com/example/App.java:
package com.example;
public class App {
public static void main(String[] args) {
System.out.println(greeting("World"));
}
static String greeting(String name) {
return "Hello, " + name + "!";
}
}Step 4: Build and run
From the project folder, run:
gradle build
gradle runThe build command compiles the code, runs the tests, and makes a JAR file in build/libs/. The run command prints Hello, World!. Gradle puts all its output in the build/ folder, where Maven uses target/.
Exercise
You move the main class to com.example.Main. Which line in build.gradle.kts must you change, and to what?
Show answer
The line in the application block. Change it to mainClass = "com.example.Main" so the run task can find the new class.
Exercise
Your computer has JDK 21 on the PATH, but the build script has languageVersion = JavaLanguageVersion.of(17). Which Java version compiles the code?
Show answer
Java 17. The toolchain block tells Gradle to use a Java 17 JDK, whatever JDK is on the PATH.