Running source files without compiling

suggest change

The classic way to run Java is two steps: compile with javac, which writes .class files, then start the JVM with java and a class name. For a small tool, a test idea or a script that is more ceremony than you need.

Since Java 11 (JEP 330) the java launcher can run a source file directly:

java Hello.java

The launcher compiles the file in memory, without writing .class files, and runs it. Java 22 (JEP 458) extended this from one file to whole programs: classes in other .java files are found and compiled when the program needs them. Together this is called source-file mode (or source launcher).

Everything here is standard, not preview. Single-file programs need Java 11 or later, multi-file programs Java 22 or later. Output is from JDK 25.

Related articles: The Java Command - java and javaw and The javac command - getting started cover the classic two-step workflow. Maven and Gradle is where you go once a program outgrows source-file mode. Java 25 also lets the launched file be a "compact source file" with an instance void main() and no class declaration. That is covered in the article "Compact source files and instance main methods". The examples here use ordinary classes, and everything works the same way with compact files.

Running a single file

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello from Java " + Runtime.version().feature());
        System.out.println("args: " + String.join(", ", args));
    }
}
> java Hello.java one "two words" 3
Hello from Java 25
args: one, two words, 3

No Hello.class appears next to Hello.java. The compiled bytes live only in the memory of the JVM that runs them.

The launcher switches to source-file mode when the first argument that is not an option ends in .java. The rules for the command line are:

> java Hello.java --enable-preview -cp x
Hello from Java 25
args: --enable-preview, -cp, x

JVM options such as -Xmx64m or -Dkey=value work as usual when placed before the file. Exit codes pass through, so System.exit(64) gives the shell exit status 64, which matters when you use source files as scripts.

The file name doesn't need to match the class name, because nothing is written to disk.

Which class is launched

A source file can declare several top-level classes. In JDK 25 the launcher runs the first top-level class in the file if that class has a main method. If it doesn't, the launcher looks for a class named like the file.

import java.util.List;

public class Inventory {
    public static void main(String[] args) {
        List<Item> items = List.of(new Item("apple", 3), new Item("pear", 0));
        for (Item i : items) {
            System.out.println(Format.line(i));
        }
    }
}

record Item(String name, int count) {}

class Format {
    static String line(Item i) {
        return "%-6s %s".formatted(i.name(), i.count() == 0 ? "sold out" : i.count());
    }
}
> java Inventory.java
apple  3
pear   sold out

If neither rule finds a launchable class you get an error:

> java Five.java
error: can't find class: Five

> java NoMain.java
error: can't find main(String[]) or main() method in class: NoMain

The simplest habit is to put the class with main first and name the file after it.

The error mentions main() because since Java 25 main may also be an instance method without String[] args (see Compact source files and instance main methods). The rules for which main is picked are the same in source-file mode and for compiled classes.

Detecting source-file mode

The launcher sets the system property jdk.launcher.sourcefile to the path of the launched file. The classes are loaded by an in-memory class loader:

import java.nio.file.Path;

public class WhereAmI {
    public static void main(String[] args) {
        String src = System.getProperty("jdk.launcher.sourcefile");
        System.out.println("source mode: " + (src != null));
        if (src != null) {
            System.out.println("file: " + Path.of(src).getFileName());
        }
        System.out.println("loader: " + WhereAmI.class.getClassLoader().getClass().getSimpleName());
    }
}
> java WhereAmI.java
source mode: true
file: WhereAmI.java
loader: MemoryClassLoader

> javac -d out WhereAmI.java
> java -cp out WhereAmI
source mode: false
loader: AppClassLoader

A script can use the property to find files that sit next to it, whatever the current directory is.

Multi-file programs (Java 22+)

Up to Java 21 source-file mode compiled exactly one file. Referring to a class from another file failed with cannot find symbol. From Java 22 the launcher treats the directory of the launched file as the root of a source tree. When the program needs a class it can't find, the launcher looks for the matching .java file in that tree and compiles it.

multi/
  Main.java
  Stats.java
  Report.java
// Main.java
public class Main {
    public static void main(String[] args) {
        var stats = new Stats();
        for (String a : args) {
            stats.add(Integer.parseInt(a));
        }
        System.out.println(Report.format(stats));
    }
}
// Stats.java
public class Stats {
    private int count;
    private long sum;

    public void add(int n) {
        count++;
        sum += n;
    }

    public int count() { return count; }

    public double average() { return count == 0 ? 0 : (double) sum / count; }
}
// Report.java
public class Report {
    public static String format(Stats s) {
        return "count=" + s.count() + " avg=" + s.average();
    }
}
> java Main.java 4 8 15 16 23 42
count=6 avg=18.0

You only name the entry file. Stats.java and Report.java were found because Main refers to them.

What gets compiled, and when

The launched file is compiled first, together with every source file it refers to statically. If any of them has an error, nothing runs:

> java Main.java 1 2
...\multi\Report.java:3: error: cannot find symbol
        return "count=" + s.count() + " avg=" + s.avg();
                                                 ^
  symbol:   method avg()
  location: variable s of type Stats
1 error
error: compilation failed

(The launcher prints the full path to the file. It is shortened to ... here.)

That is true even if the code that uses Report never runs. A class is needed as soon as the compiler sees a reference to it.

Files that nobody refers to are never compiled. A broken Scratch.java lying around in the same directory doesn't matter until something uses it. Classes loaded by name with Class.forName are compiled when they are loaded. If such a file has errors, the launcher prints the compiler errors and stops the whole program. You can't catch this in your code:

public class Plugins {
    public static void main(String[] args) throws Exception {
        for (String name : args) {
            try {
                Class<?> c = Class.forName(name);
                Object p = c.getDeclaredConstructor().newInstance();
                System.out.println(name + " -> " + p);
            } catch (Throwable t) {
                System.out.println(name + " failed: " + t);
            }
        }
    }
}

Upper.java is valid, Broken.java contains a syntax error, and there is no Missing.java:

// Upper.java
public class Upper {
    @Override public String toString() { return "HELLO"; }
}
> java Plugins.java Upper Missing Broken
Upper -> HELLO
Missing failed: java.lang.ClassNotFoundException: Missing
...\multi\Broken.java:2: error: illegal start of type
    this does not compile
    ^
...
4 errors
error: compilation failed

Here Upper.java was compiled and loaded on demand. A class with no source file is an ordinary ClassNotFoundException. Broken.java ended the program.

Packages

If the launched file declares a package, the launcher works out the root of the source tree from the package name. The file has to sit in the matching directories:

pkg/
  src/
    com/example/app/App.java
    com/example/util/Strings.java
package com.example.app;

import com.example.util.Strings;

public class App {
    public static void main(String[] args) {
        System.out.println(Strings.title("running from the source tree"));
        System.out.println("Strings is " + Strings.class.getName());
    }
}
package com.example.util;

import java.util.Arrays;
import java.util.stream.Collectors;

public final class Strings {
    private Strings() {}

    public static String title(String s) {
        return Arrays.stream(s.split(" "))
                .map(w -> Character.toUpperCase(w.charAt(0)) + w.substring(1))
                .collect(Collectors.joining(" "));
    }
}

The current directory doesn't matter. The root is src, because App.java lives in src/com/example/app:

> java src/com/example/app/App.java
Running From The Source Tree
Strings is com.example.util.Strings

If the directories don't match the package, the launcher refuses to start:

> java wrong/App.java
error: end of path to source file does not match its package name com.example.app: wrong\App.java

If the root of the tree contains a module-info.java, the program runs as a named module and its requires clauses apply:

// module-info.java
module com.example.tool {
    requires java.net.http;
}
// com/example/tool/Tool.java
package com.example.tool;

import java.net.http.HttpClient;

public class Tool {
    public static void main(String[] args) {
        System.out.println("module: " + Tool.class.getModule().getName());
        System.out.println("client: " + HttpClient.newHttpClient().version());
    }
}
> java com/example/tool/Tool.java
module: com.example.tool
client: HTTP_2

Resources work too. getResourceAsStream("/greeting.txt") finds greeting.txt at the root of the source tree.

Source files win over stale class files

The launcher always compiles the .java files in the source tree, even when .class files compiled earlier by javac sit next to them on the class path. When you switch between the two workflows you never run outdated code by accident. Still, delete leftover .class files, because they confuse readers.

Using libraries with --class-path

Source-file mode doesn't download dependencies. Libraries go on the class path, as with compiled code. See Running a Java application with library dependencies. Without the jar, compilation fails:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.List;
import java.util.Map;

public class ToJson {
    record Book(String title, int year, List<String> tags) {}

    public static void main(String[] args) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        var book = new Book("Java Notes", 2026, List.of("java", "jdk25"));
        String json = gson.toJson(book);
        System.out.println(json);
        Map<?, ?> back = gson.fromJson(json, Map.class);
        System.out.println(back.get("tags"));
    }
}
> java ToJson.java
ToJson.java:1: error: package com.google.gson does not exist
import com.google.gson.Gson;
                      ^
...
4 errors
error: compilation failed

> java --class-path lib/gson-2.13.2.jar ToJson.java
{
  "title": "Java Notes",
  "year": 2026,
  "tags": [
    "java",
    "jdk25"
  ]
}
[java, jdk25]

The class path is used both to compile the source and to run it. A wildcard picks up every jar in a directory: java -cp "lib/*" ToJson.java. Quote it so that the shell doesn't expand it. Source files in the tree are still found as described above, so a multi-file program can use jars as well.

Long option lists can go in an argument file, which is handy for scripts:

> type java.opts
--class-path lib/gson-2.13.2.jar

> java @java.opts ToJson.java

Besides --class-path (-cp), the launcher passes these options to the in-memory compiler: --module-path, --add-modules, --add-exports, --limit-modules, --patch-module, --upgrade-module-path, --enable-preview and --source. There is no way to pass other javac options such as -Xlint or -parameters. Annotation processing is disabled, so Lombok and other annotation processors don't run.

Preview features

Preview language features need --enable-preview in source-file mode too, the same flag you would give javac and java. Primitive types in patterns are a preview feature in JDK 25 (JEP 507, third preview):

public class Exact {
    static String describe(double d) {
        return switch (d) {
            case int i -> "exactly the int " + i;
            case float f -> "fits a float: " + f;
            default -> "needs a double: " + d;
        };
    }

    public static void main(String[] args) {
        for (double d : new double[] {42.0, 0.5, 0.1}) {
            System.out.println(describe(d));
        }
    }
}
> java Exact.java
Exact.java:3: error: primitive patterns are a preview feature and are disabled by default.
        return switch (d) {
                      ^
  (use --enable-preview to enable primitive patterns)
1 error
error: compilation failed

> java --enable-preview Exact.java
exactly the int 42
fits a float: 0.5
needs a double: 0.1

The source launcher compiles for the release of the JDK it runs on. Unlike javac, it doesn't need --release 25 next to --enable-preview. Asking for an older release fails, because preview features exist only for the current one:

> java --enable-preview --source 24 Exact.java
error: invalid source release 24 with --enable-preview
  (preview language features are only supported for release 25)
error: compilation failed

Shebang scripts

On Linux, macOS and other Unix-like systems a Java program can be an executable script. Put a #! line at the top, use a file name without the .java extension, and tell the launcher which source version to use with --source:

#!/usr/bin/env -S java --source 25
import java.io.*;
import java.util.*;
import java.util.stream.*;

public class WordFreq {
    public static void main(String[] args) throws IOException {
        int top = args.length > 0 ? Integer.parseInt(args[0]) : 3;
        var reader = new BufferedReader(new InputStreamReader(System.in));
        Map<String, Long> counts = reader.lines()
                .flatMap(line -> Arrays.stream(line.toLowerCase().split("[^a-z0-9]+")))
                .filter(w -> !w.isEmpty())
                .collect(Collectors.groupingBy(w -> w, Collectors.counting()));
        counts.entrySet().stream()
                .sorted(Map.Entry.<String, Long>comparingByValue().reversed()
                        .thenComparing(Map.Entry.comparingByKey()))
                .limit(top)
                .forEach(e -> System.out.println(e.getValue() + " " + e.getKey()));
    }
}
$ chmod +x wordfreq
$ printf 'the cat and the dog\nthe end of the cat\n' | ./wordfreq 3
4 the
2 cat
1 and

The details matter:

On Windows, cmd.exe and PowerShell ignore shebang lines. There you run the same file with java --source 25 wordfreq 3, or from Git Bash or WSL, where ./wordfreq works as shown.

Limits and costs

Source-file mode compiles every time you run. Compiling takes most of the startup time:

> java Main.java 1 2          (three runs)
0.79 s, 0.70 s, 0.64 s

> javac -d out Main.java Stats.java Report.java
> java -cp out Main 1 2       (three runs)
0.13 s, 0.09 s, 0.13 s

Half a second doesn't matter for a script you run by hand. It does matter for something called in a loop or from another tool, and it grows with the amount of source.

Other limits:

When to switch to a build tool

Source-file mode is meant for the first days of a program: learning, experiments, small utilities, reproducing a bug, scripts in a repo. Switch when any of these shows up:

Because a multi-file source program already has a normal package layout, moving to compiled code is mechanical. The same tree compiles with javac and packages with jar:

$ javac -d out $(find src -name '*.java')
$ jar --create --file app.jar --main-class com.example.app.App -C out .
$ java -jar app.jar
Running From The Source Tree
Strings is com.example.util.Strings

Then move src to src/main/java and add a pom.xml or build.gradle.kts, and you have a Maven or Gradle project. See Maven and Gradle.

For trying out single expressions and APIs interactively, JShell is quicker still. Source-file mode is a good fit when you want to keep the result in a file.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents