Part 15 / Stage 3
Build tools and packaging
Goal: Package a plain
javac-compiled program as a runnable JAR by hand, then build the same project with Maven; know the standardpom.xmlanatomy and lifecycle well enough to read any real Maven project; know what Gradle and JPMS modules are for, even without running either in depth here. Time: ~5 hours
What you will learn
- Why a build tool earns its keep once a project outgrows a hand-managed classpath
- Runnable JARs:
jar --create, theMain-Classmanifest entry, andjava -jar - Maven: GAV coordinates, the standard directory layout,
pom.xmlanatomy, and the build lifecycle (compile,test,package) - Running Maven for real on this machine's pinned Maven 3.9.16:
mvn compile,mvn test,mvn package - A short, conceptual look at Gradle — not installed on this machine, flagged accordingly
- A short note on the Java Platform Module System (JPMS):
module-info.java,requires,exports - Putting it together: package a small CLI tool as a runnable JAR, then as a Maven project
About "JDK 21.0.11 Corretto, Maven 3.9.16": every
javac/jar/java/jdeps/mvncommand and output below was run for real on the exact versions pinned in../../TOOLING.md. Gradle (section 6) is the one exception, flagged where it appears — not installed on this machine, covered conceptually only.
Topics in this part
Practice
Try each one yourself first. Then check the solution.
Each exercise that packages something lives in its own folder under solutions/ (solutions/ex01/, not solutions/ex01.java) because packaging needs a source tree to compile and a place to put the built artifact — the same reason examples/jar-packaging and examples/maven-project are folders.
Exercise 1: A temperature-converter CLI, packaged as a runnable JAR
Scenario: A one-class CLI tool, built and packaged entirely by hand — no Maven yet. What to do:
- Write
Converter.java:main(String[] args)takes a mode ("c2f"or"f2c") and a numeric value, and prints the converted temperature to one decimal place. - Compile it to an
out/folder, then build a jar withjar --create --main-classpointed at it. - List the jar's contents with
jar --list, then run it withjava -jarfor both a Celsius-to-Fahrenheit and a Fahrenheit-to-Celsius conversion.
Sample output:
META-INF/
META-INF/MANIFEST.MF
Converter.class
-- run --
37.0C = 98.6F
98.6F = 37.0C
💡 Hint: javac --release 21 -d out Converter.java, then jar --create --file converter.jar --main-class Converter -C out . — no package means no com/acme/... folder structure inside the jar.
Exercise 2: Inspect a jar's manifest, contents, and module footprint
Scenario: A tool that genuinely uses two non-trivial JDK modules (java.net.http, java.sql — no driver jar needed to just reference java.sql.Types); inspect the jar it produces three ways.
What to do:
- Write a small
ApiPinger.javathat printsHttpClient.Version.HTTP_2andjava.sql.Types.VARCHAR. - Build it into a runnable jar the same way as exercise 1.
- Print the manifest with
unzip -p yourfile.jar META-INF/MANIFEST.MF, then runjdeps --print-module-depson the jar.
Sample output:
-- manifest --
Manifest-Version: 1.0
Created-By: 21.0.11 (Amazon.com Inc.)
Main-Class: ApiPinger
-- run --
http client default version: HTTP_2
java.sql.Types.VARCHAR = 12 (java.sql is on the module list even with no driver jar)
-- jdeps --
java.base,java.net.http,java.sql
💡 Hint: java.sql shows up in jdeps purely because the interfaces (Types, Connection, …) live in the JDK itself — only an actual database driver (a vendor's jar, like Part 11's sqlite-jdbc) is external.
Exercise 3: A three-class CLI, one jar
Scenario: An inventory total-value calculator split across three classes (Main, Product, InventoryStore) in a package — proving a jar bundles a whole compiled tree, not one .class file.
What to do:
- Write
com/acme/inventory/Product.java(a record: name, quantity, price in paise, plus atotalValuePaise()method),InventoryStore.java(holds aList<Product>, sums their totals), andMain.java(builds a small inventory and prints each product plus the grand total). - Compile all three with one
javaccall, then package the wholeout/tree into one jar with--main-classpointed atMain. - Run it.
Sample output:
Pressure cooker qty=12 Rs 1899.00 each
Non-stick pan qty=25 Rs 649.00 each
Mixer grinder qty=8 Rs 2499.00 each
Total inventory value: Rs 59005.00
💡 Hint: javac --release 21 -d out $(find com -name "*.java") compiles all three in one call; jar --list afterward should show all three .class files under com/acme/inventory/.
Exercise 4: A module that needs two JDK modules
Scenario: Turn exercise 2's logic into a proper JPMS module, declaring both JDK modules it actually needs. What to do:
- Create a module source tree:
src/com.acme.pinger/module-info.javadeclaringrequires java.net.http;,requires java.sql;,exports com.acme.pinger;. - Put a
Mainclass undersrc/com.acme.pinger/com/acme/pinger/printing the same two facts as exercise 2. - Compile with
--module-source-path, run with--module-pathand--module, then run--describe-moduleon it.
Sample output:
-- run --
module: com.acme.pinger
http client version: HTTP_2
java.sql.Types.VARCHAR = 12
-- describe-module --
com.acme.pinger file:///.../out/com.acme.pinger/
exports com.acme.pinger
requires java.net.http
requires java.sql
requires java.base mandated
(the three requires lines can print in any order run-to-run — --describe-module doesn't guarantee ordering among a module's requires entries; only exports is guaranteed to stay where shown.)
💡 Hint: the module's own directory must be named com.acme.pinger (the module name, dots included) under src/, separate from the com/acme/pinger package-path folders inside it — the two look similar but serve different purposes.
Exercise 5: Two custom modules, one requiring the other
Scenario: A small com.acme.gstlib module (just a GST calculation) and a com.acme.gstcli module that genuinely depends on it by module name, not by jar path.
What to do:
- Write
src/com.acme.gstlib/module-info.java(exports com.acme.gstlib;) and aGstclass with a staticaddGst(amount, ratePercent)method. - Write
src/com.acme.gstcli/module-info.java(requires com.acme.gstlib;) and aMainclass that callsGst.addGst(...)and prints the result. - Compile both with one
--module-source-pathcall, runcom.acme.gstcli'sMainwith an amount from the command line, and--describe-moduleboth modules.
Sample output:
-- run --
Rs 2000.00 + 18% GST = Rs 2360.00
-- describe both modules --
com.acme.gstlib file:///.../out/com.acme.gstlib/
exports com.acme.gstlib
requires java.base mandated
com.acme.gstcli file:///.../out/com.acme.gstcli/
requires com.acme.gstlib
requires java.base mandated
contains com.acme.gstcli
(the two requires lines can print in either order run-to-run — --describe-module doesn't guarantee ordering among a module's requires entries; exports/contains lines are stable.)
💡 Hint: com.acme.gstcli's own package is not exported, so --describe-module lists it as contains rather than exports — nothing outside this module can see it, which is exactly the point of JPMS's encapsulation.
Exercise 6: Write a pom.xml from scratch
Scenario: Given a GAV (com.acme:temp-logger:2.0.0) and a Main-Class (com.acme.temps.Main), write the pom.xml and matching source layout from a blank folder — no copying an existing one and relabeling it.
What to do:
- Create
src/main/java/com/acme/temps/Main.java: reads a Celsius value fromargs[0](default28.0) and prints the Fahrenheit equivalent. - Write
pom.xmlby hand: the three GAV fields,<packaging>jar</packaging>,maven.compiler.releaseset to 21, and amaven-jar-pluginconfiguration with<mainClass>com.acme.temps.Main</mainClass>. - Run
mvn package, then run the jar it produces.
Sample output:
$ mvn -q package
$ java -jar target/temp-logger-2.0.0.jar 37
37.0C = 98.6F
💡 Hint: <finalName>${project.artifactId}-${project.version}</finalName> inside <build> is what makes the produced jar's name predictable (temp-logger-2.0.0.jar) instead of Maven's default, which also includes <packaging>'s value oddly inconsistently across Maven versions — pin it explicitly.
Exercise 7 (stretch): Convert exercise 3 into a Maven project, with a real test
Scenario: Take exercise 3's three-class inventory tool and move it into the Maven standard layout, adding a genuine JUnit 5 test this time (Part 10's testing habit, now inside a real build). What to do:
- Move
Product,InventoryStore,Mainintosrc/main/java/com/acme/inventory/, unchanged. - Write
src/test/java/com/acme/inventory/ProductTest.javawith at least two@Testmethods: one provingtotalValuePaise()multiplies quantity by price correctly, one provingInventoryStore.totalValuePaise()sums every product. - Write
pom.xml: GAVcom.acme:inventory-tool:1.0.0, ajunit-jupitertest-scoped dependency,maven-surefire-plugin, andmaven-jar-pluginwith<mainClass>com.acme.inventory.Main</mainClass>. - Run
mvn package(it runs theProductTesttests as part of thetestphase, before packaging), then run the jar it produces.
Sample output:
$ mvn -B package
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.015 s -- in com.acme.inventory.ProductTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
$ java -jar target/inventory-tool-1.0.0.jar
Pressure cooker qty=12 Rs 1899.00 each
Non-stick pan qty=25 Rs 649.00 each
Mixer grinder qty=8 Rs 2499.00 each
Total inventory value: Rs 59005.00
💡 Hint: mvn package already includes the test phase (section 3's lifecycle) — a failing ProductTest would fail the whole package command before a jar is even built.
Show the solutions for Part 15 (18 files)
solutions/ex01/Converter.java
// Exercise 1: a Celsius<->Fahrenheit CLI, packaged as a runnable jar.
// Lives in its own folder (not solutions/ex01.java) because packaging needs a
// source tree to compile and a place to put the built jar, same reason
// examples/jar-packaging is a folder rather than one file.
public class Converter {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("usage: Converter <c2f|f2c> <value>");
return;
}
double value = Double.parseDouble(args[1]);
switch (args[0]) {
case "c2f" -> System.out.printf("%.1fC = %.1fF%n", value, value * 9 / 5 + 32);
case "f2c" -> System.out.printf("%.1fF = %.1fC%n", value, (value - 32) * 5 / 9);
default -> System.out.println("unknown mode: " + args[0] + " (use c2f or f2c)");
}
}
}
solutions/ex02/ApiPinger.java
// Exercise 2: a tool whose own code touches two non-trivial JDK modules
// (java.net.http and java.sql), packaged as a jar, then inspected: manifest,
// contents, and jdeps --print-module-deps.
import java.net.http.HttpClient;
import java.sql.Types;
public class ApiPinger {
public static void main(String[] args) {
System.out.println("http client default version: " + HttpClient.Version.HTTP_2);
System.out.println("java.sql.Types.VARCHAR = " + Types.VARCHAR + " (java.sql is on the module list even with no driver jar)");
}
}
solutions/ex03/com/acme/inventory/InventoryStore.java
package com.acme.inventory;
import java.util.List;
public class InventoryStore {
private final List<Product> products;
public InventoryStore(List<Product> products) {
this.products = products;
}
public long totalValuePaise() {
return products.stream().mapToLong(Product::totalValuePaise).sum();
}
public List<Product> products() {
return products;
}
}
solutions/ex03/com/acme/inventory/Main.java
// Exercise 3: a three-class CLI (Main, Product, InventoryStore) compiled with
// one javac invocation and packaged into a single runnable jar -- proving a
// jar bundles a whole compiled tree, not just one class.
package com.acme.inventory;
import java.util.List;
public class Main {
public static void main(String[] args) {
InventoryStore store = new InventoryStore(List.of(
new Product("Pressure cooker", 12, 189900),
new Product("Non-stick pan", 25, 64900),
new Product("Mixer grinder", 8, 249900)));
for (Product product : store.products()) {
System.out.printf("%-20s qty=%-3d Rs %.2f each%n", product.name(), product.quantity(), product.pricePaise() / 100.0);
}
System.out.printf("Total inventory value: Rs %.2f%n", store.totalValuePaise() / 100.0);
}
}
solutions/ex03/com/acme/inventory/Product.java
package com.acme.inventory;
public record Product(String name, int quantity, long pricePaise) {
long totalValuePaise() {
return quantity * pricePaise;
}
}
solutions/ex04/src/com.acme.pinger/com/acme/pinger/Main.java
package com.acme.pinger;
import java.net.http.HttpClient;
import java.sql.Types;
public class Main {
public static void main(String[] args) {
System.out.println("module: " + Main.class.getModule().getName());
System.out.println("http client version: " + HttpClient.Version.HTTP_2);
System.out.println("java.sql.Types.VARCHAR = " + Types.VARCHAR);
}
}
solutions/ex04/src/com.acme.pinger/module-info.java
// Exercise 4: a module that genuinely needs two non-java.base JDK modules.
module com.acme.pinger {
requires java.net.http;
requires java.sql;
exports com.acme.pinger;
}
solutions/ex05/src/com.acme.gstcli/com/acme/gstcli/Main.java
package com.acme.gstcli;
import com.acme.gstlib.Gst;
public class Main {
public static void main(String[] args) {
double amount = args.length > 0 ? Double.parseDouble(args[0]) : 1000.0;
System.out.printf("Rs %.2f + 18%% GST = Rs %.2f%n", amount, Gst.addGst(amount, 18.0));
}
}
solutions/ex05/src/com.acme.gstcli/module-info.java
// A consumer module: requires the library module by name, not by jar path --
// JPMS resolves it from whatever is on the module path at launch.
module com.acme.gstcli {
requires com.acme.gstlib;
}
solutions/ex05/src/com.acme.gstlib/com/acme/gstlib/Gst.java
package com.acme.gstlib;
public final class Gst {
private Gst() {}
public static double addGst(double amount, double ratePercent) {
return amount * (1 + ratePercent / 100.0);
}
}
solutions/ex05/src/com.acme.gstlib/module-info.java
// Exercise 5: a small library module, exporting only its API package.
module com.acme.gstlib {
exports com.acme.gstlib;
}
solutions/ex06/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.acme</groupId>
<artifactId>temp-logger</artifactId>
<version>2.0.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version>
<configuration>
<archive>
<manifest>
<mainClass>com.acme.temps.Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
solutions/ex06/src/main/java/com/acme/temps/Main.java
package com.acme.temps;
// Exercise 6: the GAV is com.acme:temp-logger:2.0.0, Main-Class is
// com.acme.temps.Main -- this file just needs to exist at the Maven-standard
// path (src/main/java/com/acme/temps/Main.java) for the pom.xml to be correct.
public class Main {
public static void main(String[] args) {
double celsius = args.length > 0 ? Double.parseDouble(args[0]) : 28.0;
System.out.printf("%.1fC = %.1fF%n", celsius, celsius * 9 / 5 + 32);
}
}
solutions/ex07/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.acme</groupId>
<artifactId>inventory-tool</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.14.5</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.6</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version>
<configuration>
<archive>
<manifest>
<mainClass>com.acme.inventory.Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
solutions/ex07/src/main/java/com/acme/inventory/InventoryStore.java
package com.acme.inventory;
import java.util.List;
public class InventoryStore {
private final List<Product> products;
public InventoryStore(List<Product> products) {
this.products = products;
}
public long totalValuePaise() {
return products.stream().mapToLong(Product::totalValuePaise).sum();
}
public List<Product> products() {
return products;
}
}
solutions/ex07/src/main/java/com/acme/inventory/Main.java
package com.acme.inventory;
import java.util.List;
public class Main {
public static void main(String[] args) {
InventoryStore store = new InventoryStore(List.of(
new Product("Pressure cooker", 12, 189900),
new Product("Non-stick pan", 25, 64900),
new Product("Mixer grinder", 8, 249900)));
for (Product product : store.products()) {
System.out.printf("%-20s qty=%-3d Rs %.2f each%n", product.name(), product.quantity(), product.pricePaise() / 100.0);
}
System.out.printf("Total inventory value: Rs %.2f%n", store.totalValuePaise() / 100.0);
}
}
solutions/ex07/src/main/java/com/acme/inventory/Product.java
package com.acme.inventory;
public record Product(String name, int quantity, long pricePaise) {
long totalValuePaise() {
return quantity * pricePaise;
}
}
solutions/ex07/src/test/java/com/acme/inventory/ProductTest.java
package com.acme.inventory;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class ProductTest {
@Test
void totalValueIsQuantityTimesPrice() {
Product cooker = new Product("Pressure cooker", 12, 189900);
assertEquals(12L * 189900, cooker.totalValuePaise());
}
@Test
void storeTotalsAllProducts() {
InventoryStore store = new InventoryStore(java.util.List.of(
new Product("A", 2, 10000),
new Product("B", 3, 5000)));
assertEquals(2 * 10000 + 3 * 5000, store.totalValuePaise());
}
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Forgetting --main-class on jar --create |
The jar works, but only with java -cp file.jar Main.Class.Name — java -jar fails with "no main manifest attribute" |
Pass --main-class, or add Main-Class: to a manifest file manually |
Treating target/ (Maven) like a source folder |
It's entirely regenerated by the build; anything you put there by hand is deleted on the next mvn clean |
Put source in src/main/java; never edit anything under target/ |
A test dependency (JUnit) with no <scope>test</scope> |
It (and everything it pulls in) ships inside your production jar for no reason | Always scope test-only dependencies as test |
Assuming mvn package runs tests only if you ask it to |
package already includes the test phase (section 3's lifecycle) — a failing test fails mvn package too |
Expect it; use mvn test alone when you only want the test result |
| Writing Gradle commands from memory, untested, as if they were verified | This course does not have Gradle installed; nothing in section 6 was run | Keep section 6 strictly conceptual until Gradle is actually installed and checked here |
Assuming a Maven "could not resolve plugin" or "could not resolve dependency" error means the pom.xml is wrong |
It almost always means the configured repository is slow, unreachable, or missing that exact version — not that the file is malformed | Check network/repository configuration first; the error message always names the exact artifact and repository URL it tried and failed to reach |
Adding a module-info.java to a small app "because JPMS is modern" |
Real cost (every dependency and its dependencies must also be modules, or explicitly treated as automatic modules), no benefit at this project size | Skip it unless the project is genuinely large enough to need strong encapsulation between its own parts |
Quick recap
- A build tool automates dependency resolution, compiling, testing and packaging as one repeatable command — Part 11's one-hand-added jar is exactly the problem this stops being manageable once there's more than one dependency.
- A runnable JAR is a zip of
.classfiles plus a manifest;jar --create --main-classwrites theMain-Class:entry that letsjava -jarskip naming the class to run. - Maven's GAV coordinates (
groupId:artifactId:version), fixed directory layout, andpom.xmldescribe a project once; the lifecycle (validate → compile → test → package → install → deploy) runs every earlier phase automatically. mvn packagegenuinely needs network access the first time, to download the plugins and dependencies that do the actual work — once cached in~/.m2/repository, later builds are fast and offline.- JPMS (
module-info.java,requires,exports) adds real encapsulation value for large, multi-team codebases; small projects (including this course's) are fine on the default unnamed module. - Gradle solves the same problem as Maven with a task-graph model and a Kotlin/Groovy build file — covered here conceptually only, since it isn't installed or verified on this machine.
- The exact same compiled program can be packaged by hand or by Maven with identical runtime behavior — the build tool changes the process around the code, not the code's own behavior.
Checklist
- I built a runnable JAR by hand with
jar --create --main-classand ran it withjava -jar. - I can name all three GAV coordinates and explain Maven's standard directory layout from memory.
- I can list the build lifecycle phases in order and say which ones
mvn packageruns for you. - I ran
mvn packageon a real project on my own machine (not just read this lesson's transcript) and ran the jar it produced. - I can read a
build.gradle.ktsfile's shape even though I haven't run Gradle myself yet. - I wrote a
module-info.javawith at least onerequiresand oneexports, and ran the result with--module-path. - I packaged the same small CLI tool two ways (hand-built jar, Maven project) and confirmed both produce identical runtime behavior.