What is JBang? The Complete Guide to Java Scripting
Introduction
Java is a powerful language, but traditionally it hasn't been known for rapid scripting or prototyping. The verbosity and boilerplate code have often been cited as reasons why developers turn to Python, JavaScript, Bash, or other languages for scripting tasks.
JBang is a tool that changes this perception by making Java a first-class citizen in the scripting world. Created by Max Andersen, JBang addresses a simple question: why should writing a quick Java utility require more ceremony than Python or Bash?

In this comprehensive guide, you'll learn what JBang is, how it compares to alternatives, and how to leverage its full potential for your development workflow.
What is JBang?
JBang is a command-line tool that transforms Java into a scripting language, making it as accessible as Python or Shell scripting. It allows developers to create, edit, and run self-contained Java programs with minimal setup. There's no need for project configuration or build files.
By eliminating the need for traditional build tools like Maven or Gradle for simple scripts, JBang simplifies Java development, enabling experimentation and quick prototyping. Whether you're writing a quick one-off script or prototyping an idea, JBang allows you to work in plain Java syntax while automatically managing dependencies and even JDK versions.
With JBang, you can:
- Run Java code directly from
.javafiles, URLs, or even Maven coordinates - Manage dependencies inline using simple comment directives (
//DEPS) or annotations - Support multiple languages including Java, Kotlin, Groovy, JShell, and Markdown
- Create native executables using GraalVM native-image
- Debug and edit scripts seamlessly in popular IDEs like IntelliJ IDEA, VS Code, and Eclipse
- Share scripts via the JBang App Store and catalogs
Its tagline, "Unleash the power of Java," perfectly encapsulates its mission to make Java more approachable for scripting and lightweight tasks.
JBang vs JShell vs Java Single-File
Java offers several options for running code without a full project setup. Understanding the differences helps you choose the right tool for your needs.
JShell (Java 9+)
JShell is Java's built-in REPL (Read-Eval-Print Loop), introduced in Java 9. While useful for quick experimentation, it has significant limitations for scripting:
- Poor error handling: JShell ignores syntax errors and proceeds with execution, returning exit code 0 regardless of failures
- Difficult argument passing: Passing command-line arguments to JShell scripts requires workarounds
- No dependency management: You cannot easily include external libraries without manual classpath configuration
Java Single-File Source-Code Programs (JEP 330, Java 11+)
Java 11 introduced JEP 330, allowing you to run single .java files directly without explicit compilation:
java HelloWorld.javaThis approach is more robust than JShell. Syntax errors and exceptions properly return non-zero exit codes. However, it still lacks dependency management; you must distribute any required JARs separately.
JBang: The Complete Solution
JBang combines the best of both approaches while adding powerful features neither can offer:
| Feature | JShell | Java Single-File (JEP 330) | JBang |
|---|---|---|---|
| Requires installation | No (built-in) | No (built-in) | Yes |
| Dependency management | No | No | Yes (//DEPS) |
| Error handling | Poor (always exits 0) | Good | Good |
| Command-line arguments | Difficult | Easy | Easy |
| Auto-download JVM | No | No | Yes |
| IDE support | Basic | Basic | Full |
| Multiple languages | No | No | Yes (Java, Kotlin, Groovy) |
| Native image support | No | No | Yes (GraalVM) |
| Script sharing | No | No | Yes (App Store, catalogs) |
If you need dependency management, JBang is the way to go.
Why Use JBang?
For years, Java developers have lacked a simple scripting solution. JBang fills this gap with features such as:
- Ease of Use: Write a standalone
.javafile with a main method and run it immediately - Automatic Dependency Management: Resolve dependencies from Maven Central or other repositories with simple comments (e.g.,
//DEPS ...) - Cross-Platform: Works on Windows, macOS, Linux, and AIX. True "Write once, run anywhere"
- JDK Bootstrapping: No Java installed? JBang can download and install the required JDK for you
- Modern Java Support: Use preview features, latest Java versions, and compile-time options
- Framework Integration: Compatible with Quarkus, Spring Boot, Micronaut, and Apache Camel
- CI/CD Ready: Run JBang scripts in GitHub Actions, GitLab CI, or any CI/CD pipeline
- Native Image Compilation: Create standalone native executables with GraalVM
Getting Started with JBang
Let's get JBang installed and running on your system.
Installation
JBang offers multiple installation methods for different platforms:
Linux/macOS/AIX/WSL (bash):
curl -Ls https://sh.jbang.dev | bash -s - app setupWindows PowerShell:
iex "& { $(iwr -useb https://ps.jbang.dev) } app setup"Package Managers:
sdk install jbangbrew install jbangdev/tap/jbangchoco install jbangscoop install jbangImportant
Consider verifying the script's source and checksum before execution for security best practices.
Alternatively, you can download the JBang binaries for your system directly from the website.
After installation, verify JBang is correctly installed:
jbang --versionWriting Your First Script
Let's create a simple "Hello, World!" script using JBang.
1. Initialize the Script
JBang provides a simple way to create a new script:
jbang init HelloWorld.javaThis creates a file named HelloWorld.java with a basic template:
///usr/bin/env jbang "$0" "$@" ; exit $?
import static java.lang.System.*;
public class HelloWorld {
public static void main(String... args) {
out.println("Hello World");
}
}2. Run the Script
Execute the script with:
jbang HelloWorld.javaYou should see Hello World in your terminal.
On Unix-like systems, you can also make the script executable and run it directly:
chmod +x HelloWorld.java
./HelloWorld.javaThe shebang line (///usr/bin/env jbang "$0" "$@" ; exit $?) tells the system to use JBang to run the script.
JBang Script Directives
JBang scripts use special comments (directives) to configure behavior. These must appear at the beginning of the file, before any code.
Dependency Management
The //DEPS directive adds Maven dependencies to your script:
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS info.picocli:picocli:4.7.6
//DEPS com.google.code.gson:gson:2.11.0
import picocli.CommandLine;
import com.google.gson.Gson;
public class WithDependencies {
public static void main(String... args) {
System.out.println("Dependencies loaded successfully!");
}
}JBang automatically downloads dependencies from Maven Central and adds them to the classpath.
Custom Repositories
Use //REPOS to add custom Maven repositories:
//REPOS central,jitpack
//REPOS custom=https://repo.company.com/maven2
//DEPS com.github.user:repo:tagJava Version
Specify the required Java version with //JAVA:
//JAVA 21 // Exact version
//JAVA 17+ // Minimum version (17 or higher)JBang automatically downloads the required JDK version if not available on your system.
Preview Features
Enable preview features for experimenting with the latest Java capabilities:
//JAVA 23+
//PREVIEW
void main() {
System.out.println("Using simplified main with preview features!");
}Complete Directives Reference
Here's a comprehensive table of all available JBang directives:
| Directive | Description | Example |
|---|---|---|
//DEPS | Add Maven dependencies | //DEPS org.slf4j:slf4j-api:2.0.9 |
//REPOS | Specify Maven repositories | //REPOS jitpack,central |
//SOURCES | Include additional source files | //SOURCES utils/*.java |
//FILES | Include resource files | //FILES config.properties |
//JAVA | Specify Java version | //JAVA 21+ |
//PREVIEW | Enable preview features | //PREVIEW |
//COMPILE_OPTIONS | Set compiler options | //COMPILE_OPTIONS -Xlint:all |
//RUNTIME_OPTIONS | Set JVM runtime options | //RUNTIME_OPTIONS -Xmx2g |
//NATIVE_OPTIONS | GraalVM native-image options | //NATIVE_OPTIONS --no-fallback |
//MAIN | Override default main class | //MAIN com.example.App |
//MANIFEST | Add JAR manifest entries | //MANIFEST Built-By=Developer |
//GAV | Maven coordinates for script | //GAV com.example:app:1.0.0 |
//DESCRIPTION | Script description | //DESCRIPTION A utility script |
//KOTLIN | Specify Kotlin version | //KOTLIN 2.0.21 |
//GROOVY | Specify Groovy version | //GROOVY 4.0.24 |
//CDS | Enable Class Data Sharing | //CDS |
//JAVAAGENT | Configure Java agent | //JAVAAGENT myagent.jar |
Multi-Language Support
JBang isn't limited to Java. It also supports multiple JVM languages.
Kotlin
Create and run Kotlin scripts:
jbang init -t hello.kt HelloKotlin.kt
jbang HelloKotlin.ktYou can control the Kotlin version:
//KOTLIN 2.0.21
fun main() {
println("Hello from Kotlin!")
}Groovy
Create Groovy scripts:
jbang init -t hello.groovy HelloGroovy.groovy
jbang HelloGroovy.groovySpecify the Groovy version:
//GROOVY 4.0.24
println "Hello from Groovy!"Markdown
You can even "run" Markdown files! JBang extracts and executes Java or JShell code blocks:
jbang init -t readme.md README.md
jbang README.mdThis is great for executable documentation and tutorials.
GraalVM Native Images
JBang can compile your scripts to native executables using GraalVM's native-image tool. The resulting binaries launch in milliseconds, have a smaller memory footprint, and run independently without a JVM installation.
Creating a Native Image
jbang --native HelloWorld.javaThe first run compiles the native image (which takes longer). Subsequent runs use the cached native binary for instant startup.
Customizing Native Compilation
Use the //NATIVE_OPTIONS directive for fine-tuning:
///usr/bin/env jbang "$0" "$@" ; exit $?
//NATIVE_OPTIONS --no-fallback -O2
//NATIVE_OPTIONS -H:+ReportExceptionStackTraces
public class NativeApp {
public static void main(String... args) {
System.out.println("Running as native binary!");
}
}Prerequisites for Native Images
You need GraalVM with native-image installed:
# Install via SDKMan
sdk install java 21.0.2-graalce
sdk use java 21.0.2-graalce
# Or download from graalvm.org and install native-image
gu install native-imageNative images are ideal for CLI tools, serverless functions, and container images with minimal size.
IDE Integration
JBang integrates seamlessly with popular IDEs for a full development experience.
VS Code
Install the JBang VS Code extension for syntax highlighting, dependency completion, and debugging support.
IntelliJ IDEA
The JBang IntelliJ plugin provides full IDE support, including code completion for dependencies and run configurations.
Opening Scripts in IDE
Use the edit command to open any script with full IDE support:
jbang edit HelloWorld.javaJBang creates a temporary project with proper classpath configuration, giving you code completion, debugging, and refactoring capabilities.
JBang App Store and Catalogs
JBang includes a powerful system for sharing and discovering scripts.
The JBang App Store
The JBang App Store allows you to discover and run scripts published by the community:
# Run cowsay
jbang cowsay@jbangdev "Hello JBang!"
# Run JReleaser
jbang jreleaser@jreleaser
# Search Maven Central
jbang gavsearch@jbangdev hibernateCreating Aliases
Create local aliases for frequently used scripts:
jbang alias add --name hello https://github.com/jbangdev/jbang-examples/blob/HEAD/examples/helloworld.java
jbang helloCatalog Files
Share collections of scripts via jbang-catalog.json:
{
"aliases": {
"hello": {
"script-ref": "HelloWorld.java",
"description": "A simple hello world script"
},
"cli": {
"script-ref": "MyCLI.java",
"description": "Command-line utility"
}
}
}Host this file in a Git repository, and others can use your scripts:
jbang hello@user/repoInstalling as System Commands
Install JBang scripts as system-wide commands:
jbang app install hello.java
hello # Now available as a commandFramework Integration
JBang works seamlessly with popular Java frameworks.
Quarkus
Create a single-file Quarkus REST API:
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS io.quarkus.platform:quarkus-bom:3.17.7@pom
//DEPS io.quarkus:quarkus-rest
//JAVA 17+
//Q:CONFIG quarkus.http.port=8080
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
@Path("/hello")
public class QuarkusApp {
@GET
public String hello() {
return "Hello from Quarkus!";
}
}Run it:
jbang QuarkusApp.java
# Visit http://localhost:8080/helloApache Camel
Install Camel JBang and run integration routes:
# Install Camel CLI
jbang app install camel@apache/camel
# Run a route
camel run route.yamlExample YAML route:
- from:
uri: "timer:tick?period=1000"
steps:
- set-body:
constant: "Hello Camel!"
- log: "${body}"Picocli CLI
Create professional command-line applications:
jbang init -t cli MyCLI.javaThis generates a script with Picocli for argument parsing, help generation, and shell completion.
CI/CD Integration
JBang is perfect for automation scripts in CI/CD pipelines.
GitHub Actions
Use the official JBang GitHub Action:
name: Run JBang Script
on: [push]
jobs:
jbang:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Run JBang script
uses: jbangdev/jbang-action@v0.135.1
with:
script: myscript.java
scriptargs: "arg1 arg2"Docker
Run JBang scripts in containers:
docker run -v $(pwd):/scripts jbangdev/jbang-action /scripts/myscript.javaExporting to Maven or Gradle
When your script grows into a full project, export it to a traditional build system:
Export to Gradle
jbang export gradle --group com.example --artifact myapp hello.javaExport to Maven
jbang export maven --group com.example --artifact myapp hello.javaJBang converts your //DEPS directives to proper pom.xml or build.gradle dependencies.
Other Export Formats
# Create a fat JAR
jbang export fatjar hello.java
# Create a portable package
jbang export portable hello.java
# Create a JLink runtime image
jbang export jlink hello.java
# Export to Maven repository
jbang export mavenrepo hello.javaReal-World Use Cases
JBang excels in scenarios where traditional Java setup is overkill:
DevOps Automation
Replace complex shell scripts with type-safe Java:
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS info.picocli:picocli:4.7.6
//DEPS org.zeroturnaround:zt-exec:1.12
import picocli.CommandLine;
import picocli.CommandLine.Command;
import org.zeroturnaround.exec.ProcessExecutor;
@Command(name = "deploy", description = "Deploy blog")
public class deploy implements Runnable {
@CommandLine.Option(names = {"-e", "--env"}, required = true)
String environment;
public void run() {
System.out.println("Deploying blog.marcnuri.com to " + environment);
// Your deployment logic here
}
public static void main(String... args) {
new CommandLine(new deploy()).execute(args);
}
}Quick Prototyping
Test libraries without creating a project:
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS com.squareup.okhttp3:okhttp-jvm:5.3.2
import okhttp3.*;
public class TestLibrary {
public static void main(String... args) throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://blog.marcnuri.com")
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}Educational Demos
Share executable examples via URLs:
jbang https://github.com/marcnuri-demo/blog-tutorials/blob/main/Demo.javaStudents can run examples without any setup.
Frequently Asked Questions
Do I need Java installed to use JBang?
No! JBang can automatically download and manage Java for you. If Java isn't installed, JBang downloads the required version on first run.
Can I use JBang with my existing Maven/Gradle project?
JBang is designed for standalone scripts, but you can:
- Use
jbang export maven|gradleto convert scripts to projects - Use the JBang Maven/Gradle plugins to run scripts from existing projects
What's the difference between JBang and JShell?
JBang offers dependency management, multiple language support, native image compilation, and proper error handling. JShell is built-in but limited to interactive exploration without external dependencies.
Can I use JBang in production?
Absolutely! JBang is used in production for CLI tools, automation scripts, and microservices. For production deployments, consider exporting to native images or traditional build systems.
How do I debug JBang scripts?
Use jbang edit to open your script in an IDE with full debugging support, or run with jbang --debug script.java and attach a remote debugger.
Can I use private Maven repositories?
Yes, use the //REPOS directive to add private repositories:
//REPOS private=https://repo.company.com/maven2For authentication, configure your ~/.m2/settings.xml as you would for Maven.
Conclusion
JBang brings the convenience of scripting languages to Java without sacrificing any of its power. Whether you're automating DevOps tasks, testing a new library, prototyping an idea, or introducing Java to newcomers, JBang eliminates the setup overhead that has historically made Java feel heavyweight for quick tasks.
Key takeaways:
- Zero setup: Run Java files directly without project configuration
- Dependency management: Add libraries with simple
//DEPScomments - Multi-language: Support for Java, Kotlin, Groovy, and more
- Native images: Compile to standalone executables with GraalVM
- IDE support: Full development experience in VS Code, IntelliJ, and Eclipse
- CI/CD ready: GitHub Actions, Docker, and pipeline integration
Give JBang a try and see how it can streamline your Java development workflow!
Official Resources:
