Part 15 / Topic 2 of 7
Runnable JARs: jar, Main-Class, and java -jar
A JAR (Java ARchive) is a zip file of compiled .class files, with one extra file: META-INF/MANIFEST.MF. Add a Main-Class entry to that manifest, and java -jar yourfile.jar knows which class to run — no -cp and no class name needed at the command line.
Think of a shipped appliance versus a box of loose parts: the parts (.class files) are the same either way, but the appliance (the jar, with a manifest) comes with a label saying which button starts it.
$ javac --release 21 -d out src/com/acme/billsplit/BillSplitter.java
$ jar --create --file billsplit.jar --main-class com.acme.billsplit.BillSplitter -C out .
$ jar --list --file billsplit.jar
META-INF/
META-INF/MANIFEST.MF
com/
com/acme/
com/acme/billsplit/
com/acme/billsplit/BillSplitter.class
$ unzip -p billsplit.jar META-INF/MANIFEST.MF
Manifest-Version: 1.0
Created-By: 21.0.11 (Amazon.com Inc.)
Main-Class: com.acme.billsplit.BillSplitter
$ java -jar billsplit.jar 2400 4 10
Bill: Rs 2400.00
Tip (10.0%): Rs 240.00
Grand total: Rs 2640.00
Split 4 ways: Rs 660.00 per person
-C out . tells jar to change into out and add everything from there — the same -C idea as tar. --main-class writes the Main-Class: line into the manifest for you; without it, the jar still works with java -cp billsplit.jar com.acme.billsplit.BillSplitter, it just can't be run with the shorter java -jar form.
jdeps (java dependency analysis, bundled with the JDK) lists which JDK modules a jar actually uses — useful input to a custom runtime image (jlink, not covered in this course) or just to know a jar's real footprint:
$ jdeps --print-module-deps billsplit.jar
java.base
BillSplitter only touches java.base (every class in java.lang, java.util, and friends) — no networking, no I/O beyond System.out, so that's the entire list.
⚠️ A jar with no
Main-Classis not broken — it just isn't directly runnable. Library jars (the kind Maven downloads as dependencies) never declare aMain-Class; there is no single "the" class to run in a library. Only an application jar needs one.
Full project: examples/jar-packaging/ (src/com/acme/billsplit/BillSplitter.java; run the three commands above from inside that folder).
Done here? The practice set for Part 15 — including the solutions — is on the part page.