HOWTO · Java

How to Create and Run a Java JAR File

Learn how to compile a Java class, package it into an executable JAR, run it with java -jar, and launch a class from a JAR with an explicit classpath.

On this page

A Java JAR packages compiled classes and related resources in one archive. To create and run an executable JAR, write a class with a main method, compile it with javac, package it with a Main-Class entry, then launch it with java -jar.

Create and Run an Executable Java JAR

Create this source file at src/MyClass.java:

public class MyClass {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

From a clean project directory, create the output directory with mkdir -p out, then compile the class into it with javac -d out src/MyClass.java. Create the executable archive with jar cfe MyApplication.jar MyClass -C out .. The c flag creates the archive, f names the archive file, and e sets the entry point class. The command records Main-Class: MyClass in the manifest and adds the compiled files from out.

Run it from that directory with java -jar MyApplication.jar. The call to println writes its argument to standard output when the program runs.

Expected output:

Hello, World!

Run a JAR Without an Executable Manifest

A JAR does not need a Main-Class entry if you start the class yourself. Package the same compiled output without the entry point using jar cf MyApplication.jar -C out ., then specify both the archive and class name when launching it: java -cp MyApplication.jar MyClass.

Here, -cp sets the classpath and MyClass names the class whose main method Java should call. This is useful when the archive is a library or when you want to choose the entry point at launch time. It differs from java -jar: that option uses the main class recorded in the archive’s manifest and does not use a separately supplied class name.

Verify the JAR and Handle Common Questions

Use jar tf MyApplication.jar to list the archive contents. An executable JAR should include MyClass.class and a manifest at META-INF/MANIFEST.MF; inspect that manifest with an archive utility to confirm it contains the exact entry Main-Class: MyClass. For a classpath-based JAR, the manifest need not name a main class, but the class you specify with -cp must be present in the archive or another classpath location.

A JAR is a ZIP-based archive for Java class files, resources, and metadata. java -jar starts the class named by its manifest, while java -cp lets you name a class directly. Double-clicking a JAR may work on a desktop system only when a Java runtime and suitable file association are configured; launching from a terminal makes the selected command and any diagnostic messages visible.