To build a JAR from source code, you compile the project's .java files with a JDK, then package the resulting .class files and resources into a ZIP-format archive using the jar tool (or a build tool like Maven or Gradle that automates both steps). The key condition is that your project must be compilable against a known Java version, and any third-party dependencies must be resolved before packaging if you want a runnable JAR. This guide walks through the manual path first, then shows how build tools and executable-JAR manifests fit in, because most real projects use one of those rather than raw javac and jar commands.
The term "JAR" stands for Java ARchive. Internally it is a ZIP file with a META-INF/MANIFEST.MF metadata file, so anything that produces a correct class layout inside a ZIP with that manifest can be treated as a JAR. That fact matters later: when a build fails or a JAR misbehaves, the fix usually comes down to what is inside the archive, not the packaging command itself.
What You Need Before Running Any Commands
A JDK, not just a JRE, is the baseline requirement. The JDK ships javac (the compiler) and jar (the archiver), and you can confirm both are on your path by running javac -version and jar --version in a terminal. If either command is missing, the JDK isn't installed or isn't on PATH; install a current JDK distribution for your platform and reopen the terminal.
Beyond the JDK, confirm three things about the source tree:
1: The layout. Find where the .java files live and whether they declare package statements. A file declaring package com.example.util; must sit under a directory path ending in com/example/util/, or you must compile with source-path options that resolve it. 2: The source level. Check whether the project targets a specific Java release (often noted in a pom.xml, build.gradle, or README). Compiling newer syntax with an older JDK fails; compiling with a much newer JDK can produce class files older runtimes can't load. 3: The dependencies. Look for pom.xml, build.gradle, or a lib/ folder of JARs. Plain source code with imports from third-party packages won't compile without those JARs on the classpath.
If the project already has a build file, skip the manual steps entirely and jump to the build-tool section. Manual compilation is for small projects, learning exercises, or situations where you need to understand what the tooling is doing.
The Manual Path: Compile First, Package Second
This sequence is the most transparent way to build a JAR. It works well for a handful of files and exposes exactly where failures originate.
Step 1 — Create a clean output directory. From the project root, run mkdir -p out. Compiling into a dedicated directory keeps generated .class files separate from source, which makes packaging predictable.
Step 2 — Compile all sources into that directory. On a Unix-like shell:
javac -d out $(find src -name "*.java")
On Windows PowerShell:
javac -d out (Get-ChildItem -Recurse -Filter *.java src | ForEach-Object { $_.FullName })
The -d out flag tells javac to place each class file at the path implied by its package declaration, creating subdirectories as needed. Add -cp with dependency JARs if imports require them, for example -cp "lib/*" on Unix or -cp "lib*" on Windows.
Step 3 — Verify the compile succeeded. Check that out now contains .class files in package-shaped folders and that javac printed no errors. A common failure here is package X does not exist, which almost always means a dependency JAR is missing from -cp or the package's directory structure doesn't match its declaration.
Step 4 — Copy resources if the project has them. Non-code files such as .properties, images, or XML configs need to be placed in the same package-shaped locations under out. A config.properties that belongs beside a class in com/example goes into out/com/example/config.properties. Forgetting this step produces a JAR that compiles and packages fine but throws missing-resource errors at runtime.
Step 5 — Create the JAR. Run jar --create --file app.jar -C out . from the project root. Older documentation uses jar cf app.jar -C out ., which is equivalent. The -C out . part changes into out and archives everything there, avoiding the classic mistake of jar cf app.jar out producing entries like out/com/... that break package resolution at runtime.
Step 6 — Inspect the result. Run jar --list --file app.jar to see the entries. You should see META-INF/MANIFEST.MF, then package folders and class files. If the listing starts with out/, your paths are wrong and the JAR won't load classes correctly.
Step 7 — Test it on the classpath. For a library JAR, run a small check such as java -cp app.jar com.example.Main if there's a main class, or write a tiny throwaway class that imports from the JAR and run it with the JAR on -cp. Success means the classes resolve and load. A NoClassDefFoundError at this stage points to a missing dependency or a mistyped package path; a ClassNotFoundException in the main entry suggests a wrong class name or an entry-point problem rather than a packaging one.
A stop condition worth respecting: if the project vendors native libraries, uses annotation processors, or has a multi-module structure with inter-module dependencies, the manual path gets fragile fast. At that point, use the project's build tool rather than hand-assembling the JAR.
Making the JAR Executable With a Manifest
Plain java -cp app.jar com.example.Main requires callers to know the main class. An executable JAR lets them run java -jar app.jar instead, which reads the entry point from the manifest's Main-Class attribute.
The jar tool's --main-class option writes that attribute during creation:
jar --create --file app.jar --main-class com.example.Main -C out .
If the manifest also needs a classpath entry (for example, Class-Path: lib/dependency.jar), write a small manifest text file with lines like Main-Class: com.example.Main and Class-Path: lib/dependency.jar, then pass --manifest manifest.txt (or the older m manifest.txt) during creation. Keep in mind that manifest Class-Path entries are space-separated and relative to the JAR's location, not the working directory.
The executable JAR check is simple: java -jar app.jar should run the same way java -cp app.jar com.example.Main did. If the first fails and the second succeeds, the manifest is the problem — inspect it with jar --extract --file app.jar META-INF/MANIFEST.MF and read the extracted file. A trailing space or line-continuation mistake in Main-Class is a frequent cause.
There is a well-known limitation here: a Main-Class manifest does not bundle dependencies. An executable JAR built this way still needs its dependency JARs present at the paths named in Class-Path. The common fix is a "fat" or "uber" JAR, which physical copies dependencies into the archive; Maven's Shade plugin and Gradle's Shadow plugin handle that, while jar alone does not.
Using Maven When the Project Has a pom.xml
Maven projects declare source layout, compiler release, and dependencies in pom.xml, so the tool derives everything the manual path needed you to specify. From the project root, run mvn package. Maven compiles into target/classes, copies resources, and writes a JAR to target/ named from the artifact coordinates — typically -.jar.
A few expectations and checks:
Run mvn -q package for quieter output, or mvn package -DskipTests to bypass tests when you only need the archive; skipping tests is a deliberate trade-off, not a default. Look for BUILD SUCCESS and confirm a .jar appears in target/. BUILD FAILURE with a compiler plugin error means the source level or dependencies don't match; read the error line, which names the offending file and option. For a runnable artifact, check whether the POM configures maven-jar-plugin with a mainClass; if not, the JAR is a library and you run it with -cp.
Because the reference date here is late 2026, version-specific guidance matters: Maven plugins such as the compiler plugin have their own release cadence, and a pom.xml written years earlier may pin plugin versions that predate the JDK you're using. If compilation fails on unsupported release flags, update the compiler plugin's source/target (or release) configuration to a version your JDK supports rather than downgrading the JDK without checking the project's compatibility notes.
Using Gradle When the Project Has build.gradle
For Gradle projects, run gradle build (or ./gradlew build if the wrapper is present, which is preferable because it pins a known Gradle version). The wrapper is the safer choice: ./gradlew build uses the project's declared Gradle version, so behavior doesn't drift with whatever Gradle is installed globally.
Build output lands in build/libs/. If the build file applies the application plugin, you also get start scripts and a distribution; if it configures the Shadow plugin, you get an uber JAR. Confirm success by checking for the JAR and running ./gradlew build --scan only if the project is configured for scan publishing — otherwise just inspect the artifact and test it as in the manual path.
The same stop condition applies: annotation-processor-heavy or multi-module builds are best left to the tool. Gradle will fail with a task-specific error naming the missing configuration, and editing the build file blindly to silence it risks producing an archive that's technically valid but behaviorally wrong.
Runnable JARs With Dependencies: What Changes
When the source imports external libraries, "build a JAR" splits into two questions: package only your classes, or package everything? Each choice has consequences.
| Approach | Command/tool | Result | Trade-off |
|---|---|---|---|
| Thin JAR | jar or Maven default | Your classes only | Needs dependencies on Class-Path at runtime; smaller, easier to update |
| Fat JAR | Maven Shade, Gradle Shadow | Your classes plus dependencies | Self-contained but larger; duplicate resources and license-notice handling need care |
| Modular JAR | jar with module-info.class | Explicit module boundaries | Requires JPMS-aware code and tooling; not needed for most applications |
The fat-JAR failure worth knowing: two dependencies that ship the same resource path (for example, identically named META-INF/services entries) can silently overwrite each other, breaking service-loader lookups. Shade's transformers and Shadow's merge rules exist for this reason. After building a fat JAR, the practical check is the same as before — java -jar — plus verifying that a feature relying on a merged service file still works.
For modular projects, compile with javac --module-path ... --module-source-path ... and package with jar --create --file app.jar --main-class module.Main -C out ., letting the module-info.class land in the archive. This is a distinct workflow; don't mix it into a plain classpath build without also addressing --module-path at runtime.
Common Failures and How to Diagnose Them
Treat symptoms as clues to categories rather than specific causes.
"package does not exist" at compile time. Likely causes, in order of plausibility: missing -cp entry, wrong directory layout relative to package declarations, or a JAR that isn't present in the location you named. Start with a reversible check — print the classpath you passed and verify the JAR files exist there — before modifying anything.
"No suitable method found" or syntax errors against a modern JDK. Often a source-level mismatch. Check the project's declared release; if it's older than the JDK you compiled with, confirm whether the project intends to support that release and adjust --release accordingly, or use the matching JDK.
JAR built but classes not found at runtime. Inspect the archive listing. If entries include a leading directory from your working directory (like out/ or the project name), rebuild with -C out .. If META-INF/MANIFEST.MF is missing, the jar command didn't complete or you created a ZIP another way.
Executable JAR runs but can't find a dependency. The manifest's Class-Path is relative to the JAR's location and space-separated. Reproduce the path exactly and test with java -jar from the JAR's directory before concluding the dependency is missing.
Fat JAR runs but a plugin or service stops working. Resource collision at merge time. Check which dependencies provide the same path and apply the build tool's merge/transformer configuration.
If any of these checks fail after two rounds of adjustment and the project uses a build tool, stop experimenting and read the project's own build documentation and CI configuration. A CI file that produces a working artifact is authoritative evidence of the intended command, and the local environment — JDK version, tool version, environment variables — is likely the discrepancy.
What a Working Build Looks Like When You're Done
Success isn't "a file named something.jar exists." A working build satisfies five checks: the compile reported zero errors; the archive listing shows package-shaped entries and a META-INF/MANIFEST.MF at the root; the expected class or entry point loads when run with -cp or -jar; any resources the code reads at startup are present inside the archive; and if the JAR is published, the coordinates and version in its name match what the build tool declared. Run all five and record the command that produced the artifact — reproducing the build later depends on knowing the exact step and tool version you used.
From here, the natural next step depends on intent. For learning, repeat the manual flow with a small multi-package project and add one dependency to see the classpath change in action. For a real project, adopt the project's build tool and pin it with a wrapper. For distribution, decide between thin and fat JARs based on whether consumers can supply dependencies themselves, and document the choice in the manifest and build configuration so the next person rebuilding the JAR doesn't have to rediscover it.