Programming languages · Intermediate · 24 min
Build a Java project with Gradle and the Kotlin DSL
By Padding · Updated 26 Nov 2026
Ubuntu (eclipse-temurin:25-jdk image) · Temurin 25.0.5 · Gradle 9.9.2
You will build a two-module Java 25 bill splitter with Gradle 9.9, with a pinned wrapper, a version catalog, JUnit 6 tests, cached builds and a runnable distribution that builds on a fresh clone.
On this page
Gradle is a build tool: it compiles your code, runs your tests, fetches libraries and packages the result. Its builds are written as code, and with the Kotlin DSL that code lives in .gradle.kts files that your editor can autocomplete and check. Two ideas make Gradle different from a plain script. It models the build as a graph of tasks with declared inputs and outputs, so it can skip any task whose inputs have not changed. And it can store task outputs in a build cache, so a clean build on the same machine, or on a teammate's, can reuse work instead of redoing it.
In this tutorial you build a small bill splitter in Java 25. It divides a total between people so the shares add up to the exact amount, down to the last cent, which matters when a group splits a restaurant bill or a shared data bundle. The project has two modules: core, a library with the splitting logic and its tests, and app, a command-line program that uses it. Along the way you read every build file Gradle writes, pin the Gradle Wrapper with a checksum, move versions into a catalog, and see why implementation and api are different. If you have done the Maven tutorial, this is the same kind of app with a different tool, and the last section compares the two.
Step 1 · Install Gradle 9.9.2
You need a local Gradle only once, to create the project. After that the project carries its own Gradle through the wrapper. Install the tools the next steps use, then download the Gradle 9.9.2 distribution from the official site and check its SHA-256 checksum before you unpack it. The checksum comes from Gradle's own release data, so a damaged or tampered download fails here instead of running on your machine.
sudo apt update
sudo apt install -y curl unzip git
cd /tmp
curl -fLO https://services.gradle.org/distributions/gradle-9.9.2-bin.zip
echo "971fcd7150ca4ba04852c0b2ca0d2d0ab9468e14b03473eab19528809914c76b gradle-9.9.2-bin.zip" | sha256sum -c -
sudo mkdir -p /opt/gradle
sudo unzip -q -o -d /opt/gradle gradle-9.9.2-bin.zip
rm gradle-9.9.2-bin.zipsha256sum -c prints gradle-9.9.2-bin.zip: OK. Any other answer means the file is not the one Gradle published: delete it and download again. On macOS, use shasum -a 256 -c - in place of sha256sum -c -.
Put Gradle on your PATH for this shell and for future logins:
export PATH=/opt/gradle/gradle-9.9.2/bin:$PATH
echo 'export PATH=/opt/gradle/gradle-9.9.2/bin:$PATH' >> ~/.profileA Gradle unpacked by hand gets no security updates from apt. You will rarely run it directly, because each project's wrapper decides its own Gradle version, and Step 3 shows how to move a project to a newer one. To upgrade this copy, repeat the download with the new version number and its checksum from the Gradle releases page.
Check it worked
gradle --versionThe output starts with Gradle 9.9.2 and has a Launcher JVM: line that names Java 25, something like 25.0.5. If it names an older Java, set JAVA_HOME to your Java 25 install and run it again.
Step 2 · Generate a project and read what Gradle wrote
Create a throwaway folder and let gradle init generate a Java application. The flags answer the questions it would otherwise ask: a Java application, Kotlin DSL build files, JUnit Jupiter tests, Java 25, one application module, and no incubating (still-changing) Gradle APIs.
mkdir -p ~/bill-splitter-demo
cd ~/bill-splitter-demo
gradle init --type java-application --dsl kotlin --test-framework junit-jupiter \
--package dev.example.app --project-name bill-splitter --java-version 25 \
--no-split-project --no-incubating
ls -aYou now have these files. The ones you will change are marked.
settings.gradle.kts(you rewrite it) names the build and lists its modules, which Gradle calls projects. It is the first file Gradle reads.app/build.gradle.kts(you rewrite it) is the build script for theappmodule: which plugins it applies, where its dependencies come from, which Java version it targets and which class holdsmain.gradle/libs.versions.toml(you rewrite it) is the version catalog, one place for every library version in the build.gradlew,gradlew.batandgradle/wrapper/are the Gradle Wrapper.gradle-wrapper.propertiesrecords which Gradle version this project uses, and the scripts download that version on first use.app/src/main/java/dev/example/app/App.javaand a test next to it inapp/src/testare a sample class and test.gradle.properties(you replace it) holds build settings;gradle initturns on the configuration cache here withorg.gradle.configuration-cache=true..gitignore(you replace it) and.gitattributeskeep Gradle's local folders out of Git and fix line endings for the wrapper scripts.
Open settings.gradle.kts and app/build.gradle.kts and read them now. The comments gradle init adds explain each block, and the rest of this tutorial replaces them with files you write yourself, so you know what every line does.
Run the sample through the wrapper rather than the gradle on your PATH:
./gradlew runThe first run prints Downloading https://services.gradle.org/distributions/gradle-9.9.2-bin.zip while the wrapper fetches its own copy of Gradle into ~/.gradle/wrapper/dists. That download is about 135 MB, once per Gradle version per machine, on top of the copy you fetched in Step 1. With the libraries and plugins the later steps fetch, plan for roughly 300 MB in total. Libraries are cached in ~/.gradle/caches the same way. On prepaid mobile data, do the first build of a project on Wi-Fi; after that, ./gradlew build --offline works from the caches with no network at all.
Check it worked
The build ends with BUILD SUCCESSFUL and prints the sample's greeting, something like Hello World!. ls -a lists .gitattributes, .gitignore, app, gradle, gradle.properties, gradlew, gradlew.bat and settings.gradle.kts.
Step 3 · Pin the wrapper with a checksum
The wrapper is what makes a Gradle project reproducible: everyone who runs ./gradlew, and every CI server, gets the Gradle version written in gradle/wrapper/gradle-wrapper.properties. Ask the wrapper task to record the distribution's checksum too, so the wrapper refuses a download that does not match:
./gradlew wrapper --gradle-version 9.9.2 \
--gradle-distribution-sha256-sum 971fcd7150ca4ba04852c0b2ca0d2d0ab9468e14b03473eab19528809914c76b
cat gradle/wrapper/gradle-wrapper.propertiesThis is also how you upgrade a project later: run the same command with the new version and its checksum, then commit the changed wrapper files. Commit gradlew, gradlew.bat and the whole gradle/wrapper/ folder, including gradle-wrapper.jar. Without them, nobody else can build the project with a plain ./gradlew.
Check it worked
The properties file has a distributionUrl ending in gradle-9.9.2-bin.zip and a distributionSha256Sum=971fcd71... line.
Step 4 · Split the build into two modules with a version catalog
Replace the generated settings with your own. It declares Maven Central once for every module and includes two modules, core and app:
cat > settings.gradle.kts <<'KTS'
rootProject.name = "bill-splitter"
dependencyResolutionManagement {
repositories {
mavenCentral()
}
}
include("core", "app")
KTSNow the version catalog. [versions] holds version numbers, and [libraries] gives each library an alias. Gradle turns the dashes in an alias into dots, so commons-lang3 becomes libs.commons.lang3 in build scripts. The JUnit entries have no version of their own: they take it from the JUnit BOM (bill of materials), so all JUnit pieces always match.
cat > gradle/libs.versions.toml <<'TOML'
[versions]
commons-lang3 = "3.22.0"
junit = "6.1.3"
[libraries]
commons-lang3 = { module = "org.apache.commons:commons-lang3", version.ref = "commons-lang3" }
junit-bom = { module = "org.junit:junit-bom", version.ref = "junit" }
junit-jupiter = { module = "org.junit.jupiter:junit-jupiter" }
junit-platform-launcher = { module = "org.junit.platform:junit-platform-launcher" }
TOMLThe core module is a library, so it applies the java-library plugin. The java { toolchain { ... } } block says this module is compiled and tested with Java 25, whatever JVM happens to run Gradle itself. Gradle looks for a matching JDK on your machine and fails with a clear message if there is none. (Gradle can also download one through a toolchain resolver plugin; see its toolchains guide.)
mkdir -p core
cat > core/build.gradle.kts <<'KTS'
plugins {
`java-library`
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(25)
}
}
dependencies {
implementation(libs.commons.lang3)
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testRuntimeOnly(libs.junit.platform.launcher)
}
tasks.test {
useJUnitPlatform()
testLogging {
events("passed", "failed")
}
}
KTSimplementation, testImplementation and testRuntimeOnly are configurations: named buckets of dependencies, each with its own job. testRuntimeOnly puts the JUnit launcher on the classpath when tests run but not when they compile, because no test code refers to it.
Write the splitting logic. It works in whole cents so nothing is lost to rounding: 100.00 between three people is 10,000 cents, which is 3,333 each with 1 cent left over, and the first person pays that cent. receipt uses commons-lang3 to line the columns up.
mkdir -p core/src/main/java/dev/example/split
cat > core/src/main/java/dev/example/split/BillSplitter.java <<'JAVA'
package dev.example.split;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
public final class BillSplitter {
private BillSplitter() {}
/** Splits total into shares that add up to exactly total. Earlier people pay any extra cent. */
public static List<BigDecimal> split(BigDecimal total, int people) {
if (people < 1) {
throw new IllegalArgumentException("people must be at least 1");
}
if (total.signum() < 0) {
throw new IllegalArgumentException("total must not be negative");
}
long cents = total.setScale(2, RoundingMode.HALF_EVEN).unscaledValue().longValueExact();
long base = cents / people;
long extra = cents % people;
List<BigDecimal> shares = new ArrayList<>();
for (int i = 0; i < people; i++) {
shares.add(BigDecimal.valueOf(base + (i < extra ? 1 : 0), 2));
}
return List.copyOf(shares);
}
/** One line per person: the name, then the share right-aligned. */
public static String receipt(List<String> names, List<BigDecimal> shares) {
if (names.size() != shares.size()) {
throw new IllegalArgumentException("one share per name");
}
int width = names.stream().mapToInt(String::length).max().orElse(0);
StringBuilder out = new StringBuilder();
for (int i = 0; i < names.size(); i++) {
out.append(StringUtils.rightPad(names.get(i), width))
.append(StringUtils.leftPad(shares.get(i).toPlainString(), 10))
.append('\n');
}
return out.toString();
}
}
JAVANow the app module. It applies the application plugin, depends on core with project(":core"), and names its main class. The generated sample test checks the old greeting, so delete app/src/test first; this removes only the sample gradle init wrote.
rm -rf app/src/test
cat > app/build.gradle.kts <<'KTS'
plugins {
application
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(25)
}
}
dependencies {
implementation(project(":core"))
}
application {
mainClass = "dev.example.app.App"
}
KTS
mkdir -p app/src/main/java/dev/example/app
cat > app/src/main/java/dev/example/app/App.java <<'JAVA'
package dev.example.app;
import dev.example.split.BillSplitter;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
public final class App {
public static void main(String[] args) {
if (args.length < 2) {
System.err.println("usage: app <total> <name> [<name> ...]");
System.exit(2);
}
BigDecimal total = new BigDecimal(args[0]);
List<String> names = Arrays.asList(args).subList(1, args.length);
System.out.print(BillSplitter.receipt(names, BillSplitter.split(total, names.size())));
}
}
JAVACheck it worked
List the projects, then run the app with a total and three names:
./gradlew projects
./gradlew run --args="100 Ada Kofi Zainab"projects lists Project ':app' and Project ':core' under the root project bill-splitter. The run prints Ada with 33.34, then Kofi and Zainab with 33.33 each: three shares that add up to exactly 100.00.
Step 5 · Test the library with JUnit 6
Add tests to core. The first checks the 100-between-three case exactly. The second is a parameterised test that runs once per CSV row and checks that the shares always add back up to the total. The third checks that zero people is rejected.
mkdir -p core/src/test/java/dev/example/split
cat > core/src/test/java/dev/example/split/BillSplitterTest.java <<'JAVA'
package dev.example.split;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.math.BigDecimal;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class BillSplitterTest {
@Test
void firstPersonPaysTheLeftoverCent() {
List<BigDecimal> shares = BillSplitter.split(new BigDecimal("100.00"), 3);
assertEquals(
List.of(new BigDecimal("33.34"), new BigDecimal("33.33"), new BigDecimal("33.33")),
shares);
}
@ParameterizedTest
@CsvSource({"0.01, 4", "2500, 7", "19.99, 2", "1500.50, 6"})
void sharesAddUpToTheTotal(String total, int people) {
BigDecimal sum = BillSplitter.split(new BigDecimal(total), people).stream()
.reduce(BigDecimal.ZERO, BigDecimal::add);
assertEquals(0, sum.compareTo(new BigDecimal(total)));
}
@Test
void rejectsZeroPeople() {
assertThrows(IllegalArgumentException.class, () -> BillSplitter.split(BigDecimal.TEN, 0));
}
}
JAVA
./gradlew :core:test:core:test is a task path: the test task of the core project. Running plain ./gradlew test runs test in every project that has one.
Check it worked
The output has a PASSED line for each test, something like BillSplitterTest > firstPersonPaysTheLeftoverCent() PASSED, with one line per CSV row for the parameterised test, and ends with BUILD SUCCESSFUL. Gradle also writes an HTML report you can open in a browser:
ls core/build/reports/tests/test/index.htmlTo see a failure, change "33.34" to "33.35" in the test, run ./gradlew :core:test again, read the message, and change it back.
Step 6 · See the difference between implementation and api
core declares commons-lang3 with implementation. That means: core needs it to compile and run, but it is a private detail. Projects that use core get the library on their runtime classpath, so the app runs, but not on their compile classpath, so they cannot write code against it by accident. Compare the two classpaths of app:
./gradlew :app:dependencies --configuration compileClasspath
./gradlew :app:dependencies --configuration runtimeClasspathCheck it worked
Under compileClasspath, project :core has nothing beneath it. Under runtimeClasspath, it has org.apache.commons:commons-lang3:3.22.0 beneath it.
Now prove it. Add a class to app that calls commons-lang3 directly and try to compile it:
cat > app/src/main/java/dev/example/app/Shout.java <<'JAVA'
package dev.example.app;
import org.apache.commons.lang3.StringUtils;
final class Shout {
static String loud(String s) {
return StringUtils.upperCase(s);
}
}
JAVA./gradlew :app:compileJavaThe build fails with error: package org.apache.commons.lang3 does not exist. That is implementation doing its job. If app really needs the library, it should declare its own dependency on it. Switch core to api(libs.commons.lang3) only when the library is part of core's public interface: for example, if a public method of BillSplitter returned a commons-lang3 type, every caller would need that type to compile. To use api, a module must apply java-library, not plain java.
Keeping dependencies on implementation where you can has a practical pay-off: when you upgrade an implementation-only library in core, Gradle does not need to recompile app. Delete the experiment before you go on:
rm app/src/main/java/dev/example/app/Shout.java
./gradlew :app:compileJavaThe second command ends with BUILD SUCCESSFUL again.
Step 7 · Watch Gradle skip work it has already done
Build everything twice in a row. build compiles, tests and packages every module. --console=plain prints one line per task with its outcome, which makes skipped work easy to see.
./gradlew build --console=plain
./gradlew build --console=plainOn the second run, every task that does work ends in UP-TO-DATE (tasks with nothing to work on, such as :core:processResources, say NO-SOURCE), and the summary reads N actionable tasks: N up-to-date, with the same number twice. Gradle compared each task's inputs (source files, dependencies, compiler settings) and outputs with the last run, found nothing changed, and did not run them. Edit a file in app only and build again: core's tasks stay UP-TO-DATE and only app's compile and packaging tasks run.
Up-to-date checks only compare with the last run in the same folder. ./gradlew clean deletes the build folders, and then everything runs again. The build cache goes further: it stores task outputs by a key computed from their inputs, so any later run with the same inputs can reuse them, even after a clean or in a different checkout. Turn it on for this project in gradle.properties. This command replaces the file gradle init wrote, so the configuration cache line goes; that is fine for this build, and you can add org.gradle.configuration-cache=true back on its own line if you want both:
cat > gradle.properties <<'PROPS'
org.gradle.caching=true
PROPS
./gradlew clean build --console=plain
./gradlew clean build --console=plainThe first clean build runs every task and fills the cache in ~/.gradle/caches. The second deletes the outputs again, but the compile and test tasks now end in FROM-CACHE: Gradle copied their outputs out of the cache instead of compiling and testing again.
Check it worked
The last command's output has lines such as > Task :core:compileJava FROM-CACHE and > Task :core:test FROM-CACHE.
Step 8 · Package a distribution with the application plugin
The application plugin does more than run. installDist builds a folder with start scripts for Linux, macOS and Windows plus every jar the app needs, and distZip packs the same folder into a zip you can hand to someone:
./gradlew :app:installDist :app:distZip
app/build/install/app/bin/app 2500 Amara Chidi Fatima Kwame Lindiwe Tendai Yusuf
unzip -l app/build/distributions/app.zipThe start script needs a Java 25 runtime on the machine where it runs, found through JAVA_HOME or java on the PATH. On Windows, use bin\app.bat.
Check it worked
The script prints seven lines: Amara and Chidi with 357.15, the other five with 357.14. That is 2,500.00 split seven ways, with the 2 leftover cents paid by the first two people. The zip lists app/bin/app, app/bin/app.bat and, under app/lib/, app.jar, core.jar and commons-lang3-3.22.0.jar.
Step 9 · Build it from a fresh clone, then clean up
The real test of a build is whether someone else can run it with nothing but Git and a JDK. Write a .gitignore that keeps build outputs and Gradle's local state out of the repository (this replaces the one gradle init wrote with the two lines this build needs), then commit everything else:
cat > .gitignore <<'IGNORE'
.gradle/
build/
IGNORE
git init -q -b main
git add .
git commit -q -m "Bill splitter built with Gradle"
git ls-filesgit ls-files should include gradlew, gradle/wrapper/gradle-wrapper.jar and gradle/wrapper/gradle-wrapper.properties, and no build folders.
Clone it to a new folder, as a teammate or CI server would, and build there with the wrapper. In a real project you clone from your Git host instead of a local folder:
git clone -q ~/bill-splitter-demo ~/bill-splitter-fresh
cd ~/bill-splitter-fresh
./gradlew build --console=plainCheck it worked
The fresh clone builds with BUILD SUCCESSFUL. Because gradle.properties was committed with caching on, and the cache lives in your home folder, most tasks in the clone come FROM-CACHE even though this folder has never been built.
When you have finished, stop the background Gradle daemon and delete both demo folders. This removes only what this tutorial created:
./gradlew --stop
cd ~
rm -rf ~/bill-splitter-demo ~/bill-splitter-freshIf you will not use Gradle again on this machine, the next command also deletes the hand-installed Gradle and ~/.gradle. Be careful: ~/.gradle holds the wrapper downloads, dependency cache and build cache for every Gradle project on this machine, so skip it if you have others. Then remove the export PATH=/opt/gradle/... line from ~/.profile in your editor.
sudo rm -rf /opt/gradle
rm -rf ~/.gradleNext steps
You now have a two-module Gradle build with a pinned, checksummed wrapper, versions in one catalog, JUnit 6 tests, up-to-date checks and caching, and a distribution that builds from a fresh clone.
Gradle or Maven? Pick Maven when you want a fixed, declarative lifecycle that every Java developer already knows, a single pom.xml per module, and little room for custom logic; it suits libraries and services with ordinary builds. Pick Gradle when builds are large or multi-module and speed matters (up-to-date checks and the build cache pay off most there), when you need custom tasks written as code, or when you work with Kotlin or Android, where Gradle is the default. Both read from Maven Central, so the libraries are the same either way.
- Build the same kind of project the other way in Build and test a Java project with Maven.
- Try the language whose DSL you have been writing in Hello World in Kotlin.
- Put the bill data through a pipeline in Transform collections with Java streams.
When two modules repeat the same toolchain block, as core and app do here, the next Gradle idea to learn is a convention plugin in build-logic, which holds shared settings in one place.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials