Build Executable JAR in Java

Su Suriya Ravichandran Updated 18 Nov 2026
9 min read ·Lesson 265 of 306

A JAR file packages your compiled classes and resources into one file. To build executable JAR in Java projects, the JAR also needs a Main-Class entry in its manifest and a way to find its libraries, so that java -jar app.jar starts the program on any machine.

This lesson builds plain, executable, thin and fat JARs with both Maven and Gradle, shows how to inspect what ends up inside, and explains when to use each kind. It ends with a release-ready fat JAR that reports its own version. To create a JAR by hand with the jar tool, see JAR File in Java.


Types of JAR Files for Java Applications

JAR typeContainsRun withBest for
Plain JARYour classes only, no Main-Classjava -cp app.jar:libs/* MainLibraries used by other projects
Executable JARYour classes + Main-Classjava -jar app.jarApps with no external libraries
Thin JAR + lib/Your classes + Main-Class + Class-Path to lib/*.jarjava -jar app.jar (with lib/ next to it)Apps where libraries are updated separately
Fat (uber) JARYour classes + every runtime library, unpackedjava -jar app-all.jarCommand-line tools and services shipped as one file

All examples use this small app from Gradle Dependencies: it uses Gson at compile time and the H2 database driver at run time.

student-export/
└── src/main/java/com/gocourse/export/
    ├── App.java              <- main class, creates an H2 table and prints JSON
    ├── Student.java          <- record
    └── StudentExporter.java  <- reads rows with JDBC, writes JSON with Gson

How it works:

  • A JAR is a ZIP file. META-INF/MANIFEST.MF inside it holds settings such as Main-Class and Class-Path.
  • java -jar ignores -cp and the CLASSPATH variable. Everything the app needs must be reachable from the manifest, which is why libraries are the hard part.

Build a Plain JAR With Maven and Gradle

Both tools create a plain JAR as part of their normal build.

# Maven
mvn -q package
jar tf target/student-export-1.0.0.jar

# Gradle
./gradlew jar -q
jar tf build/libs/student-export-1.0.0.jar

Output (both tools list the same entries):

META-INF/
META-INF/MANIFEST.MF
com/
com/gocourse/
com/gocourse/export/
com/gocourse/export/App.class
com/gocourse/export/Student.class
com/gocourse/export/StudentExporter.class

Try to run it:

java -jar target/student-export-1.0.0.jar
no main manifest attribute, in target/student-export-1.0.0.jar

How it works:

  • jar tf lists the files inside a JAR without extracting them.
  • The JAR has no Main-Class in its manifest, so java -jar does not know which class to start.
  • Gson and H2 are not inside. Even with a Main-Class, the app would fail with NoClassDefFoundError: com/google/gson/GsonBuilder.

Add Main-Class to the Manifest

Maven: Configure the JAR Plugin

<plugin>
  <artifactId>maven-jar-plugin</artifactId>
  <version>3.5.0</version>
  <configuration>
    <archive>
      <manifest>
        <mainClass>com.gocourse.export.App</mainClass>
      </manifest>
    </archive>
  </configuration>
</plugin>

Gradle: Configure the jar Task

tasks.jar {
    manifest {
        attributes("Main-Class" to "com.gocourse.export.App")
    }
}
mvn -q package
unzip -p target/student-export-1.0.0.jar META-INF/MANIFEST.MF
java -jar target/student-export-1.0.0.jar

Output (shortened):

Manifest-Version: 1.0
Created-By: Maven JAR Plugin 3.5.0
Build-Jdk-Spec: 25
Main-Class: com.gocourse.export.App

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/gson/GsonBuilder
	at com.gocourse.export.StudentExporter.<init>(StudentExporter.java:14)
	at com.gocourse.export.App.main(App.java:18)
Caused by: java.lang.ClassNotFoundException: com.google.gson.GsonBuilder

How it works:

  • unzip -p prints one file from the JAR. On Windows, use jar xf to extract it, or open the JAR with any ZIP tool.
  • Main-Class now starts App, so java -jar gets further. The app fails at the first line that needs Gson.
  • An executable JAR with only Main-Class is enough only when the app uses nothing beyond the JDK. The next two sections add the libraries.

Build a Thin JAR With a lib Folder

A thin JAR keeps libraries as separate files in a lib/ folder and lists them in the manifest's Class-Path.

Maven: addClasspath and copy-dependencies

<plugin>
  <artifactId>maven-jar-plugin</artifactId>
  <version>3.5.0</version>
  <configuration>
    <archive>
      <manifest>
        <mainClass>com.gocourse.export.App</mainClass>
        <addClasspath>true</addClasspath>
        <classpathPrefix>lib/</classpathPrefix>
      </manifest>
    </archive>
  </configuration>
</plugin>

<plugin>
  <artifactId>maven-dependency-plugin</artifactId>
  <version>3.11.0</version>
  <executions>
    <execution>
      <id>copy-libs</id>
      <phase>package</phase>
      <goals>
        <goal>copy-dependencies</goal>
      </goals>
      <configuration>
        <outputDirectory>${project.build.directory}/lib</outputDirectory>
        <includeScope>runtime</includeScope>
      </configuration>
    </execution>
  </executions>
</plugin>
mvn -q package
unzip -p target/student-export-1.0.0.jar META-INF/MANIFEST.MF | grep -A1 Class-Path
ls target/lib
java -jar target/student-export-1.0.0.jar

Output:

Class-Path: lib/gson-2.13.2.jar lib/error_prone_annotations-2.41.0.jar l
 ib/h2-2.4.240.jar
error_prone_annotations-2.41.0.jar
gson-2.13.2.jar
h2-2.4.240.jar
[
  {
    "name": "Asha",
    "course": "Java",
    "marks": 92
  },
  {
    "name": "Ravi",
    "course": "Python",
    "marks": 78
  }
]

How it works:

  • addClasspath writes every runtime dependency into Class-Path, and classpathPrefix puts lib/ in front of each name. Manifest lines are wrapped at 72 characters, which is why lib/h2 is split across two lines.
  • copy-dependencies copies the same JARs into target/lib during package. includeScope=runtime copies compile and runtime libraries but not test ones.
  • Paths in Class-Path are relative to the JAR. Ship student-export-1.0.0.jar and the lib/ folder together.

Gradle: installDist From the application Plugin

The application plugin already builds a thin distribution with start scripts:

./gradlew installDist -q
ls build/install/student-export/lib
build/install/student-export/bin/student-export

Output (shortened):

error_prone_annotations-2.41.0.jar
gson-2.13.2.jar
h2-2.4.240.jar
student-export-1.0.0.jar
[
  {
    "name": "Asha",
...

How it works:

  • installDist copies your JAR and all runtime libraries into build/install/<name>/lib and writes a bin/ script for Linux/macOS and a .bat file for Windows.
  • The script builds the classpath and calls java for you, so no Class-Path manifest entry is needed. ./gradlew distZip packs the same folder into a ZIP for release.

Build a Fat JAR With Maven Shade or Gradle

A fat JAR unpacks every runtime library into one JAR, so there is only one file to copy and run.

Maven: maven-shade-plugin

<plugin>
  <artifactId>maven-shade-plugin</artifactId>
  <version>3.6.2</version>
  <executions>
    <execution>
      <phase>package</phase>
      <goals><goal>shade</goal></goals>
      <configuration>
        <shadedArtifactAttached>true</shadedArtifactAttached>
        <shadedClassifierName>all</shadedClassifierName>
        <transformers>
          <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
            <mainClass>com.gocourse.export.App</mainClass>
          </transformer>
          <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
        </transformers>
        <filters>
          <filter>
            <artifact>*:*</artifact>
            <excludes>
              <exclude>module-info.class</exclude>
              <exclude>META-INF/versions/*/module-info.class</exclude>
              <exclude>META-INF/*.SF</exclude>
              <exclude>META-INF/*.DSA</exclude>
              <exclude>META-INF/*.RSA</exclude>
            </excludes>
          </filter>
        </filters>
      </configuration>
    </execution>
  </executions>
</plugin>

Gradle: a Jar Task That Includes the Runtime Classpath

tasks.register<Jar>("fatJar") {
    group = "build"
    description = "Builds a runnable JAR that contains all runtime dependencies."
    archiveClassifier = "all"

    manifest {
        attributes("Main-Class" to "com.gocourse.export.App")
    }

    from(sourceSets.main.get().output)                       // your classes and resources
    dependsOn(configurations.runtimeClasspath)
    from({
        configurations.runtimeClasspath.get()
            .filter { it.name.endsWith(".jar") }
            .map { zipTree(it) }                             // unpack each library
    })

    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
    exclude("module-info.class", "META-INF/versions/*/module-info.class",
            "META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA")
}
mvn -q package && java -jar target/student-export-1.0.0-all.jar
./gradlew fatJar -q && java -jar build/libs/student-export-1.0.0-all.jar

Output (printed once by each tool):

[
  {
    "name": "Asha",
    "course": "Java",
    "marks": 92
  },
  {
    "name": "Ravi",
    "course": "Python",
    "marks": 78
  }
]

How it works:

  • Both builds keep the plain JAR and add a second file with the classifier all, so library users still get the thin JAR.
  • ServicesResourceTransformer merges META-INF/services files. JDBC drivers register themselves there, so dropping or overwriting those files would break DriverManager.
  • In Gradle, zipTree opens each library JAR so its classes are copied in. duplicatesStrategy = EXCLUDE keeps the first copy of files that several libraries share, such as META-INF/MANIFEST.MF.
  • The excludes remove module descriptors and signature files from libraries. A merged JAR cannot hold several module-info.class files, and old signatures no longer match.

Note: If two libraries ship different META-INF/services files with the same name, the Gradle task above keeps only the first. In that case, use the Shadow plugin (com.gradleup.shadow), which merges service files like Maven Shade does.


Inspect and Run an Executable JAR

Before you release a JAR, check its manifest, its contents and the Java version it needs.

CommandPurpose
jar tf app.jarList all entries
unzip -p app.jar META-INF/MANIFEST.MFPrint the manifest
jar --describe-module --file app.jarShow module information, if any
javap -v -cp app.jar com.example.Main | grep majorShow the class file version
java -jar app.jar arg1 arg2Run with arguments
javap -v -cp target/student-export-1.0.0-all.jar com.gocourse.export.App | grep major

Output:

  major version: 69

How it works:

  • Class file version 69 means Java 25 (version = Java release + 44). A user with Java 21 sees UnsupportedClassVersionError and must upgrade, or you must lower release in the build.
  • Arguments after the JAR name go to main(String[] args); JVM options such as -Xmx512m go before -jar.

Real-World Example: Build Executable JAR in Java for a Release

This release build creates student-export-1.2.0-all.jar, a fat JAR whose manifest also records the version. The app reads that version at run time, so the printed version always matches the build. The Gradle build is shown in full, followed by the matching Maven settings.

// build.gradle.kts
plugins {
    application
}

version = "1.2.0"

repositories { mavenCentral() }

java {
    toolchain { languageVersion = JavaLanguageVersion.of(25) }
}

dependencies {
    implementation("com.google.code.gson:gson:2.13.2")
    runtimeOnly("com.h2database:h2:2.4.240")
}

val mainClassName = "com.gocourse.export.App"

application {
    mainClass = mainClassName
}

tasks.register<Jar>("fatJar") {
    group = "build"
    description = "Builds the release JAR with all runtime dependencies."
    archiveClassifier = "all"

    manifest {
        attributes(
            "Main-Class" to mainClassName,
            "Implementation-Title" to project.name,
            "Implementation-Version" to project.version)
    }

    from(sourceSets.main.get().output)
    dependsOn(configurations.runtimeClasspath)
    from({
        configurations.runtimeClasspath.get()
            .filter { it.name.endsWith(".jar") }
            .map { zipTree(it) }
    })
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
    exclude("module-info.class", "META-INF/versions/*/module-info.class",
            "META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA")
}

tasks.build {
    dependsOn("fatJar")                      // every build also produces the release JAR
}
// src/main/java/com/gocourse/export/App.java
package com.gocourse.export;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class App {
    public static void main(String[] args) throws Exception {
        Package appPackage = App.class.getPackage();
        String title = appPackage.getImplementationTitle();
        String version = appPackage.getImplementationVersion();
        System.out.println(title + " " + (version != null ? version : "(development build)"));

        String jdbcUrl = "jdbc:h2:mem:school;DB_CLOSE_DELAY=-1";
        try (Connection connection = DriverManager.getConnection(jdbcUrl);
             Statement statement = connection.createStatement()) {
            statement.execute("CREATE TABLE students (name VARCHAR(50), course VARCHAR(50), marks INT)");
            statement.execute("INSERT INTO students VALUES ('Ravi', 'Python', 78), ('Asha', 'Java', 92)");
        }

        System.out.println(new StudentExporter().exportJson(jdbcUrl));
    }
}

Student.java and StudentExporter.java are unchanged from Gradle Dependencies.

The matching Maven settings add the same manifest entries to the Shade transformer:

<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
  <mainClass>com.gocourse.export.App</mainClass>
  <manifestEntries>
    <Implementation-Title>${project.artifactId}</Implementation-Title>
    <Implementation-Version>${project.version}</Implementation-Version>
  </manifestEntries>
</transformer>

Build the release and run it from a clean folder, as a user would:

./gradlew build -q
mkdir -p /tmp/release && cp build/libs/student-export-1.2.0-all.jar /tmp/release/
cd /tmp/release
java -jar student-export-1.2.0-all.jar

Output:

student-export 1.2.0
[
  {
    "name": "Asha",
    "course": "Java",
    "marks": 92
  },
  {
    "name": "Ravi",
    "course": "Python",
    "marks": 78
  }
]

During development, ./gradlew run prints null (development build) on the first line, because classes loaded from build/classes have no manifest.

How it works:

  1. One source of truth. version = "1.2.0" names the file and fills Implementation-Version. Package.getImplementationVersion() reads it back from the manifest of the JAR the class was loaded from.
  2. Everything inside. The fatJar task unpacks Gson, its annotations and H2 next to your classes, so the copied JAR runs alone in /tmp/release with no lib/ folder.
  3. Driver discovery still works. H2 registers itself through META-INF/services/java.sql.Driver. Only H2 ships that file here, so the simple Gradle task keeps it intact; the Maven build uses ServicesResourceTransformer to be safe in every case.
  4. Part of every build. tasks.build { dependsOn("fatJar") } means CI only needs to run ./gradlew build and upload build/libs/*-all.jar.
  5. Clean manifests. Excluding library signatures and module descriptors avoids SecurityException: Invalid signature file digest and module errors at startup.

The plugins that produce these JARs on the Maven side are covered in Maven Plugins, and the tasks behind them on the Gradle side in Gradle Build.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Build Executable JAR in Java and get answers drawn from it.

Signed-in readers only.