From one file to a project
Every program in this course so far has been one file, run with java Main.java. Real Java software is different in three ways. It depends on other people's code: a JSON library, a database driver, a web framework, each with its own dependencies. It has tests, often more lines of them than of the code under test, run on every change. And it is built and shipped by machines (continuous-integration servers) that must produce exactly the same result every time.
Doing all that by hand with javac -cp would be miserable, so the Java world standardised on build tools. Two dominate: Maven (2004), declarative and convention-driven, and Gradle (2008), programmable and fast. Both download dependencies from Maven Central, the public repository of Java libraries; both compile, test and package your code with one command; and both understand the same directory layout. You will meet both in your career, often in the same week.
This lesson tours the professional toolchain (build tools, JUnit, formatters, static analysis), then brings the whole course together in a complete small program written the way an experienced Java developer would write it today.
Projects, coordinates and dependencies
Both Maven and Gradle expect this layout, and following it means any Java developer can find their way around your project in seconds:
expense-split/
├── pom.xml (Maven) or build.gradle.kts + settings.gradle.kts (Gradle)
└── src/
├── main/
│ ├── java/org/example/split/Main.java
│ └── resources/ configuration files, templates
└── test/
├── java/org/example/split/MainTest.java
└── resources/Production code goes under src/main/java, tests under src/test/java, each in directories that match their package. Tests live in the same package as the code they test, so they can use package-private members, but in a separate tree, so they never ship in the product.
Definition— Coordinates
Every published library is identified by three parts: a group (usually a reversed domain, such as org.junit.jupiter), an artifact name (junit-jupiter) and a version. Written together as group:artifact:version, they let a build tool fetch exactly that library, plus the libraries it depends on (transitive dependencies), from a repository such as Maven Central.
Definition— Dependency scope
Where a dependency is needed. In Maven, compile (the default: needed to compile and run), test (only to compile and run tests), provided (supplied by the environment at run time) and runtime (not needed to compile). Gradle calls these configurations: implementation, testImplementation, compileOnly, runtimeOnly.
Definition— Build lifecycle
Maven runs builds as a fixed sequence of phases: validate, compile, test, package, verify, install, deploy. Asking for one phase runs all the earlier ones, so mvn package compiles, runs the tests, and only then builds the JAR. Gradle instead builds a graph of tasks (compileJava, test, jar, build...) and runs only those that are needed and out of date.
Maven and Gradle, side by side
A minimal Maven build file for the project at the end of this lesson. Maven files are XML and describe what the project is, not how to build it:
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>expense-split</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- use the current JUnit release from junit.org -->
<junit.version>CURRENT_JUNIT_VERSION</junit.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>${junit.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>maven.compiler.release tells the compiler to target Java 25 and to check that you only use Java 25 APIs. The JUnit BOM ("bill of materials") pins the versions of all JUnit modules in one place, so the dependency itself needs no version. Then mvn test runs the tests, mvn package produces target/expense-split-1.0.0-SNAPSHOT.jar, and mvn verify is what a CI server typically runs.
The same project with Gradle's Kotlin DSL. Gradle build files are programs, which makes custom logic easy (and, used carelessly, makes builds hard to understand):
// build.gradle.kts
plugins {
application
}
repositories {
mavenCentral()
}
dependencies {
testImplementation(platform("org.junit:junit-bom:CURRENT_JUNIT_VERSION"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(25) // Gradle finds or downloads a JDK 25
}
}
application {
mainClass = "org.example.split.Main"
}
tasks.test {
useJUnitPlatform()
}Run it with ./gradlew test or ./gradlew run. The Gradle wrapper (gradlew, gradlew.bat and a small JAR checked into the repository) downloads the exact Gradle version the project specifies, so every developer and every CI machine builds with the same tool. Maven has an equivalent, mvnw. Commit the wrapper; do not ask colleagues to install build tools by hand.
Which to choose? Many teams pick Maven for its predictability: every Maven project looks and builds the same way. Others pick Gradle for its speed (incremental builds and a build cache) and flexibility; it is also the standard for Android. Both are excellent, and the concepts transfer.
Testing with JUnit
JUnit is the standard Java testing framework. JUnit 5 introduced the Jupiter programming model used below, and JUnit 6, released in 2025, keeps it, so this applies to both. A test class for the word-wrapping function in the next program might look like this (it needs JUnit on the class path, so it is not one of the checked programs):
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class WrapTest {
@Test
void breaksBetweenWords() {
assertEquals("one two\nthree", Wrap.wrap("one two three", 8));
}
@ParameterizedTest
@ValueSource(ints = {5, 8, 13, 40})
@DisplayName("no line is longer than the width unless it is a single word")
void respectsWidth(int width) {
String text = "the quick brown fox jumps over the extraordinary dog";
for (String line : Wrap.wrap(text, width).split("\n")) {
assertTrue(line.length() <= width || !line.contains(" "), line);
}
}
@Test
void rejectsNonPositiveWidth() {
assertThrows(IllegalArgumentException.class, () -> Wrap.wrap("x", 0));
}
}@Testmarks a test method. JUnit creates a new instance of the class for every test, so tests cannot leak state into each other through fields.- Assertions compare expected and actual values and fail with a clear message. Put the expected value first.
@ParameterizedTestruns one test body for many inputs (@ValueSource,@CsvSource,@MethodSource...). The second test checks a property that should hold for every width, rather than one example; that style catches bugs that hand-picked examples miss.assertThrowschecks that bad input is rejected, the test equivalent of "validate in the constructor".@BeforeEachand@AfterEachset up and tear down per test;@Nestedgroups related tests;@Disabledskips one, with a reason.
How does JUnit find and run tests? With annotations and reflection: it scans compiled classes for methods annotated @Test, creates an instance, invokes each method, and records which ones throw. The mechanism is simple enough to build yourself, which is a good way to demystify it:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Comparator;
public class Main {
/** Marks a test method, like JUnit's @Test. Kept at run time so reflection can see it. */
@Retention(RetentionPolicy.RUNTIME)
@interface Test {}
/** The code under test: a tiny word-wrapping function. */
static String wrap(String text, int width) {
if (width <= 0) {
throw new IllegalArgumentException("width must be positive: " + width);
}
StringBuilder out = new StringBuilder();
int lineLength = 0;
for (String word : text.split(" ")) {
if (lineLength > 0 && lineLength + 1 + word.length() > width) {
out.append('\n');
lineLength = 0;
} else if (lineLength > 0) {
out.append(' ');
lineLength++;
}
out.append(word);
lineLength += word.length();
}
return out.toString();
}
static void assertEquals(Object expected, Object actual) {
if (!expected.equals(actual)) {
throw new AssertionError("expected <" + expected + "> but was <" + actual + ">");
}
}
static class WrapTests {
@Test void shortTextIsUnchanged() { assertEquals("hello world", wrap("hello world", 20)); }
@Test void breaksBetweenWords() { assertEquals("one two\nthree", wrap("one two three", 8)); }
@Test void longWordStaysWhole() { assertEquals("a\nextraordinary\nb", wrap("a extraordinary b", 5)); }
@Test void exactFitStaysOnLine() { assertEquals("ab cd", wrap("ab cd", 5)); }
@Test void deliberatelyWrong() { assertEquals("ab\ncd", wrap("ab cd", 5)); }
}
public static void main(String[] args) throws ReflectiveOperationException {
int passed = 0, failed = 0;
Method[] methods = WrapTests.class.getDeclaredMethods();
Arrays.sort(methods, Comparator.comparing(Method::getName)); // reflection order is unspecified
for (Method m : methods) {
if (!m.isAnnotationPresent(Test.class)) continue;
Object instance = WrapTests.class.getDeclaredConstructor().newInstance(); // fresh object per test
try {
m.invoke(instance);
passed++;
System.out.println("PASS " + m.getName());
} catch (InvocationTargetException e) {
failed++;
System.out.println("FAIL " + m.getName() + ": " + e.getCause().getMessage().replace("\n", "\\n"));
}
}
System.out.println(passed + " passed, " + failed + " failed");
}
}PASS breaksBetweenWords
FAIL deliberatelyWrong: expected <ab\ncd> but was <ab cd>
PASS exactFitStaysOnLine
PASS longWordStaysWhole
PASS shortTextIsUnchanged
4 passed, 1 failed@Retention(RetentionPolicy.RUNTIME) keeps the annotation in the class file so reflection can see it. The runner sorts the methods because reflection returns them in no particular order, creates a fresh instance per test, and reports each failure's message. One test is deliberately wrong, to show a failure; in a real build a failing test fails the build. JUnit adds a great deal on top (discovery across a whole project, lifecycle hooks, parameterization, parallel execution, IDE and build-tool integration, reports), but at its core it is this loop.
The wider testing toolbox
- AssertJ offers fluent assertions (
assertThat(list).hasSize(3).contains("Bao")) with excellent failure messages; many teams prefer it to JUnit's built-in assertions. - Mockito creates stand-ins ("mocks") for collaborators such as a payment gateway, so a unit test can run without the real service. Use mocks for things you do not own or cannot run in a test; overusing them produces tests that check the implementation instead of the behaviour.
- Testcontainers starts real databases, message brokers and other services in Docker containers for integration tests.
- JaCoCo measures which lines and branches the tests executed. Coverage tells you what is not tested; it cannot tell you that what is covered is tested well.
How professional Java teams work
Beyond building and testing, a typical Java team's pipeline runs several kinds of automated checks on every pull request:
- A formatter, so that nobody spends review time on spacing.
google-java-formatandpalantir-java-formatare common, usually applied by the Spotless plugin for Maven or Gradle, which can fail the build when code is not formatted. - Static analysis, which finds bugs without running the code: the compiler's own warnings (
javac -Xlint:all), Google's Error Prone (which runs inside javac), SpotBugs, PMD and Checkstyle for style rules, and services such as SonarQube that track all of these over time. - Dependency hygiene: tools that report known vulnerabilities in dependencies and keep versions current. A Java service's dependency tree often has over a hundred libraries, and most security problems come from there.
- Packaging: a JAR (or a "fat" JAR containing all dependencies), a container image, or a self-contained application built with
jlink(a trimmed runtime containing only the JDK modules you use) andjpackage(native installers).
The ecosystem around the language matters as much as the language itself. Most Java services are built on a framework: Spring Boot is the most widely used, while Quarkus, Micronaut and Helidon emphasise fast startup and small footprints, and Jakarta EE is the standards-based specification that many of them build on. Common libraries include Jackson for JSON, SLF4J with Logback for logging, and JDBC drivers for every database. Large codebases may also use the module system (module-info.java, Java 9), which lets a library declare which packages it exports and which modules it requires; most applications still use the plain class path.
Finally, the habits that separate code that lasts from code that merely works: small pull requests with tests, code review by a colleague, readable names over clever tricks, documentation of why, and upgrading the JDK regularly (from LTS to LTS at least) rather than letting a codebase fossilise on an old release.
The project: splitting shared expenses
Four friends share the costs of a weekend trip. Each expense was paid by one person and shared by some of the group. The program reads a log of expenses, works out each person's balance, and proposes a short list of payments that settles everything. It brings together most of this course: records with validating constructors, an immutable money type, parsing with good error messages, maps and streams, a greedy algorithm over a sorted list, and self-checks in the spirit of unit tests. Money is kept as a whole number of cents, so no rounding error can creep in; when an amount does not divide evenly, the leftover cents go one each to the first sharers in alphabetical order, so the shares always add up exactly.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
/** Splits a group's shared expenses and works out who should pay whom. */
public class Main {
/** An amount of money in cents. Immutable, never fractional. */
record Money(long cents) implements Comparable<Money> {
static final Money ZERO = new Money(0);
static Money parse(String text) {
String[] parts = text.strip().split("\\.");
if (parts.length > 2 || (parts.length == 2 && parts[1].length() != 2)) {
throw new IllegalArgumentException("expected an amount like 12.50, got " + text);
}
long whole = Long.parseLong(parts[0]);
long fraction = parts.length == 2 ? Long.parseLong(parts[1]) : 0;
return new Money(Math.addExact(Math.multiplyExact(whole, 100), fraction));
}
Money plus(Money other) { return new Money(Math.addExact(cents, other.cents)); }
Money minus(Money other) { return new Money(Math.subtractExact(cents, other.cents)); }
Money negate() { return new Money(-cents); }
boolean isZero() { return cents == 0; }
@Override
public int compareTo(Money other) { return Long.compare(cents, other.cents); }
@Override
public String toString() {
return (cents < 0 ? "-" : "") + Math.abs(cents) / 100 + "." + "%02d".formatted(Math.abs(cents) % 100);
}
}
/** One shared expense: who paid, how much, what for, and who shares it. */
record Expense(String payer, Money amount, String what, List<String> sharers) {
Expense {
if (amount.cents() <= 0) throw new IllegalArgumentException("amount must be positive: " + amount);
if (sharers.isEmpty()) throw new IllegalArgumentException("nobody shares " + what);
sharers = List.copyOf(sharers);
}
/** Each sharer's part. Leftover cents go one each to the first sharers in alphabetical order. */
Map<String, Money> shares() {
List<String> sorted = sharers.stream().sorted().toList();
long base = amount.cents() / sorted.size();
long leftover = amount.cents() % sorted.size();
Map<String, Money> result = new TreeMap<>();
for (int i = 0; i < sorted.size(); i++) {
result.merge(sorted.get(i), new Money(base + (i < leftover ? 1 : 0)), Money::plus);
}
return result;
}
}
/** A payment that settles part of the debts. */
record Transfer(String from, String to, Money amount) {
@Override
public String toString() { return from + " pays " + to + " " + amount; }
}
/** Parses "Amara paid 120.00 for fuel: Amara, Bao, Chidi". */
static Expense parseLine(String line) {
String[] head = line.split(":", 2);
String[] words = head[0].strip().split(" ", 5);
if (head.length != 2 || words.length != 5 || !words[1].equals("paid") || !words[3].equals("for")) {
throw new IllegalArgumentException("cannot read: " + line);
}
List<String> sharers = new ArrayList<>();
for (String name : head[1].split(",")) {
sharers.add(name.strip());
}
return new Expense(words[0], Money.parse(words[2]), words[4], sharers);
}
/** Positive balance: the group owes this person. Negative: this person owes the group. */
static Map<String, Money> balances(List<Expense> expenses) {
Map<String, Money> balance = new TreeMap<>();
for (Expense e : expenses) {
balance.merge(e.payer(), e.amount(), Money::plus);
e.shares().forEach((person, share) -> balance.merge(person, share.negate(), Money::plus));
}
return balance;
}
/** Greedy settlement: the largest debtor pays the largest creditor until everyone is even. */
static List<Transfer> settle(Map<String, Money> balances) {
Comparator<Map.Entry<String, Money>> byAmount = Map.Entry.comparingByValue();
List<Map.Entry<String, Money>> open = new ArrayList<>(balances.entrySet().stream()
.filter(e -> !e.getValue().isZero())
.map(e -> Map.entry(e.getKey(), e.getValue()))
.toList());
List<Transfer> transfers = new ArrayList<>();
while (!open.isEmpty()) {
open.sort(byAmount.thenComparing(Map.Entry.comparingByKey()));
var debtor = open.getFirst(); // most negative
var creditor = open.getLast(); // most positive
Money amount = debtor.getValue().negate().compareTo(creditor.getValue()) < 0
? debtor.getValue().negate() : creditor.getValue();
transfers.add(new Transfer(debtor.getKey(), creditor.getKey(), amount));
open.removeFirst();
open.removeLast();
Money debtorLeft = debtor.getValue().plus(amount);
Money creditorLeft = creditor.getValue().minus(amount);
if (!debtorLeft.isZero()) open.add(Map.entry(debtor.getKey(), debtorLeft));
if (!creditorLeft.isZero()) open.add(Map.entry(creditor.getKey(), creditorLeft));
}
return transfers;
}
// ---------------------------------------------------------------- self-checks
static int checks = 0;
static void check(boolean condition, String what) {
checks++;
if (!condition) throw new AssertionError("check failed: " + what);
}
static void checkRejects(Runnable action, String what) {
try {
action.run();
} catch (IllegalArgumentException expected) {
checks++;
return;
}
throw new AssertionError("should have been rejected: " + what);
}
static void selfTest() {
check(Money.parse("12.50").cents() == 1250, "parse 12.50");
check(Money.parse("7").toString().equals("7.00"), "whole amounts");
check(new Money(-5).toString().equals("-0.05"), "negative cents");
check(new Expense("A", new Money(100), "x", List.of("C", "B", "A")).shares()
.equals(Map.of("A", new Money(34), "B", new Money(33), "C", new Money(33))), "leftover cent");
checkRejects(() -> Money.parse("1.5"), "one decimal digit");
checkRejects(() -> parseLine("Amara bought fuel"), "a line without 'paid'");
Map<String, Money> even = balances(List.of(parseLine("A paid 10.00 for tea: A, B"),
parseLine("B paid 10.00 for cake: A, B")));
check(settle(even).isEmpty(), "even group needs no transfers");
}
public static void main(String[] args) {
String log = """
Amara paid 120.00 for fuel: Amara, Bao, Chidi, Dilnoza
Bao paid 45.90 for groceries: Amara, Bao, Chidi
Chidi paid 10.00 for parking: Chidi, Dilnoza
Dilnoza paid 64.00 for dinner: Amara, Bao, Chidi, Dilnoza
""";
List<Expense> expenses = log.lines().map(Main::parseLine).toList();
Money total = expenses.stream().map(Expense::amount).reduce(Money.ZERO, Money::plus);
System.out.println(expenses.size() + " expenses, total " + total);
Map<String, Money> balances = balances(expenses);
balances.forEach((person, b) -> System.out.printf(" %-8s %8s%n", person, b));
Money sum = balances.values().stream().reduce(Money.ZERO, Money::plus);
System.out.println("balances sum to " + sum);
List<Transfer> transfers = settle(balances);
transfers.forEach(t -> System.out.println(" " + t));
String perPayer = expenses.stream().collect(Collectors.groupingBy(Expense::payer, TreeMap::new,
Collectors.mapping(Expense::what, Collectors.joining(", ")))).toString();
System.out.println("paid for: " + perPayer);
selfTest();
System.out.println(checks + " self-checks passed");
}
}4 expenses, total 239.90
Amara 58.70
Bao -15.40
Chidi -56.30
Dilnoza 13.00
balances sum to 0.00
Chidi pays Amara 56.30
Bao pays Dilnoza 13.00
Bao pays Amara 2.40
paid for: {Amara=fuel, Bao=groceries, Chidi=parking, Dilnoza=dinner}
7 self-checks passedCheck the balances by hand once: Amara paid 120.00 and her shares were 30.00 (fuel), 15.30 (groceries) and 16.00 (dinner), so the group owes her 120.00 − 61.30 = 58.70. The balances sum to zero, as they must: money moves between friends but is neither created nor destroyed. The settlement step repeatedly matches the person who owes most with the person who is owed most; each transfer settles at least one person completely, so a group of n people needs at most n − 1 transfers. (Finding the absolute minimum number of transfers is a much harder problem in general; the greedy rule is the practical choice used by real expense-sharing apps.)
Things to notice about the style:
- The types carry the rules.
Moneycannot be fractional and refuses1.5(one decimal digit) because the parser checks the format;Expensecannot have a zero amount or nobody to share it; once those objects exist, the rest of the code never re-checks. - Overflow is not silent.
MoneyusesMath.addExactand friends, so an absurd amount fails loudly instead of wrapping. - Small, named methods.
parseLine,balancesandsettleeach do one thing and can be tested alone. In a Maven project they would each get JUnit tests, much like the self-checks at the end. - Deterministic output.
TreeMap, sorted sharers and explicit tie-breaking (thenComparing(Map.Entry.comparingByKey())) mean the program prints the same thing on every machine, which is what makes it testable.
To turn it into a real project: move each record into its own file in the package org.example.split, put the self-checks into MainTest as JUnit tests, read the log from a file named on the command line (Files.readAllLines(Path.of(args[0]))), and build it with either build file above.
Where to go next
You now know the language, its standard library, its concurrency model, its runtime and its tools. Some directions from here:
- Build a service. The Spring guides walk you from a first REST endpoint to data access and security. Quarkus and Micronaut have equivalent guides on their own sites.
- Go deeper into the language. Effective Java by Joshua Bloch remains the best single book on writing Java well; read it alongside the JEPs for the features added since its last edition. The Java Language Specification answers precise questions definitively.
- Follow the platform. Inside Java and dev.java publish news and deep dives from the JDK team, and the JEP index shows what is coming. Preview features such as structured concurrency are the best place to see where Java is going.
- Read real code. The JDK's own source (on GitHub as
openjdk/jdk), and well-known open-source projects such as JUnit, are full of carefully designed Java. - Join the community. Java User Groups meet in cities around the world, and many conferences publish their talks online.
Optional Christian reflection · Faithful in little
A reflection from the Christian tradition that inspires Lumenary Academy. It is not part of the mathematics and you are welcome to skip it.
A program that splits a weekend's expenses is a small thing. But "he that is faithful in that which is least is faithful also in much" (Luke 16:10, King James Version). The habits in this project (exact money, honest error messages, tests that check the arithmetic, output that does not change from machine to machine) are the same habits that keep a bank's ledger or a hospital's records trustworthy. Professional craft is mostly faithfulness in small things, repeated.
Exercises
1. Build tools, testing and a complete project
Warm-upHumanIn the standard Maven/Gradle layout, under which directory does the test class org.example.split.MainTest belong? Give the path to the directory that holds the file, starting with src.
2. Build tools, testing and a complete project
CoreHumanYou run mvn package in a project where one unit test fails. What happens?
3. Build tools, testing and a complete project
Warm-upComputationalIn the project's output, how much does Bao pay in total, in cents?
4. Build tools, testing and a complete project
CoreComputationalUsing the project's Expense.shares(), an expense of 1.00 is shared by C, B and A (listed in that order). What is A's share? Write it as the program would print it.
5. Build tools, testing and a complete project
StretchComputationalA fifth line is added to the project's log: Chidi paid 56.30 for museum: Amara. How many transfers does the program now print?
6. Build tools, testing and a complete project
CoreComputationalIn the mini test runner, the test deliberatelyWrong is fixed to assertEquals("ab cd", wrap("ab cd", 5));. How many lines of the output now begin with PASS?
7. Build tools, testing and a complete project
CoreHumanWhich pairings of tool and job are correct? Choose all that apply.
Further reading and resources
- Apache MavenThe project site, with the introduction to the build lifecycle and the standard directory layout.
- Gradle documentationBuilding Java applications, the Kotlin DSL, toolchains and the wrapper.
- JUnitThe user guide for the Jupiter programming model used in this lesson.
- Maven CentralSearch the public repository from which Maven and Gradle download libraries.
- Inside Java · OracleNews, articles and podcasts from the people who build Java.
- SpringThe most widely used application framework for Java services, with official guides.