Compact source files and instance main methods

Since Java 25, a program can be a file containing just a void main() method: no class declaration, no public static, no String[] args. The feature started in Java 21 as "unnamed classes" and is standard in Java 25 (JEP 512). This page explains what the compiler builds from such a file, then shows console input with IO, the automatic imports, how the launcher picks a main method, the compiler's rules, and running files directly from source.

Contents

What a compact source file is

The classic first Java program needs public class, public static void main(String[] args) and System.out.println before it prints a word, and each of those words needs explaining to a beginner. Java 25 separates the two things a small program actually needs, code and an entry point, from the structure large programs need. Two changes make that possible:

  • Compact source files. A .java file may contain methods and fields with no enclosing class. The compiler wraps them in an implicitly declared class: it is final, extends Object, lives in the unnamed package, has only a generated no-argument constructor, and is named after the file. Its members are ordinary instance members of that class.
  • Instance main methods. The launcher accepts a main that is not public, not static, and takes no parameters. For an instance method, it creates an object with the no-argument constructor first and then calls main on it.

A compact source file also imports every exported package of the java.base module automatically, as if it began with import module java.base;. That covers java.util, java.util.stream, java.io, java.nio.file, java.time and the rest of the core library. And Java 25 adds the class java.lang.IO with println, print and readln, so console programs need neither System.out nor a Scanner.

Nothing changes at run time. The class file produced from a compact source file is an ordinary class, and a compact file can grow into a normal class by adding class Name { ... } around its contents and the imports it uses.

History of the feature
JDKJEPName and status
11JEP 330Launch single-file source programs: java Hello.java
21JEP 445Unnamed Classes and Instance Main Methods (preview)
22JEP 463, JEP 458Implicitly Declared Classes (second preview); multi-file source programs (standard)
23JEP 477Third preview: automatic import of java.base and the IO class
24JEP 495Simple Source Files and Instance Main Methods (fourth preview)
25JEP 512Compact Source Files and Instance Main Methods (standard); IO in java.lang

On JDK 21 to 24 such files compile only with --enable-preview --release N, and details differ from version to version; on JDK 21, javac Hello.java fails with "unnamed classes are a preview feature and are disabled by default". Everything below was compiled and run on JDK 25 with no flags.

The smallest program

This is the whole content of Hello.java:

Java
// A complete program: no class declaration, no public, no static, no String[] args
void main() {
    IO.println("Hello from a compact source file");
    IO.println("Running on Java " + Runtime.version().feature());
}

Run it straight from source with java Hello.java, or compile it with javac Hello.java and run java Hello. Output:

Output
Hello from a compact source file
Running on Java 25

IO.println writes to standard output like System.out.println. Runtime.version().feature() returned 25, the feature release of the running JDK. IO is in java.lang, so it needs no import, and unlike the auto-import of java.base it can be used from ordinary classes too.

Fields, methods, records and automatic imports

A compact source file can declare fields, methods and nested types such as records at the top level, and main can call them because they are members of the same implicit class. The sentence contains "the" three times and every other word once, so the top three show how ties are ordered.

Java
// Fields, methods and records can sit at the top level of a compact source file.
// java.base is imported automatically, so List, Map and Collectors need no imports.

record WordCount(String word, long count) {
}

final String text = "the quick fox jumps over the lazy dog the end";

List<WordCount> topWords(int n) {
    Map<String, Long> counts = Arrays.stream(text.split(" "))
            .collect(Collectors.groupingBy(w -> w, TreeMap::new, Collectors.counting()));
    return counts.entrySet().stream()
            .map(e -> new WordCount(e.getKey(), e.getValue()))
            .sorted(Comparator.comparingLong(WordCount::count).reversed())
            .limit(n)
            .toList();
}

void main() {
    IO.println("words: " + text.split(" ").length);
    for (WordCount wc : topWords(3)) {
        IO.println(wc.word() + " x" + wc.count());
    }
    IO.println("class name chosen by javac: " + getClass().getName());
}

Output:

Output
words: 10
the x3
dog x1
end x1
class name chosen by javac: WordStats
  • No import statements were written for List, Map, TreeMap, Arrays, Comparator or Collectors.
  • "the" is first with 3. The other two places are a tie at 1. The counts were collected into a TreeMap, so the tied words start in alphabetical order, and because sorted is stable, "dog" and "end" won the tie.
  • getClass().getName() printed WordStats: the implicit class takes the file's name. Because it is in the unnamed package, other classes cannot refer to it by name, which is why this form suits single-file programs.
  • The record WordCount became a nested class, WordStats$WordCount in the compiled output.

Reading console input with IO.readln

IO.readln(prompt) prints a prompt and reads one line, returning null at the end of input. The program sums numbers until an empty line. For this page its input came from a file holding 12, 7.5, 30 with spaces, an empty line, and 99, so the stopping rule is visible.

Java
// Reads numbers typed by the user (here fed from a file) until an empty line or end of input
void main() {
    double total = 0;
    int count = 0;
    String line;
    while ((line = IO.readln("number> ")) != null && !line.isBlank()) {
        total += Double.parseDouble(line.strip());
        count++;
    }
    IO.println();
    IO.println(count + " numbers, total " + total + ", average " + total / count);
}

Output (input redirected from the file, so the typed numbers do not appear):

Output
number> number> number> number> 
3 numbers, total 49.5, average 16.5
  • Four prompts were printed: three for the numbers and one that read the empty line and ended the loop, so 99 was never read. The total is 12 + 7.5 + 30 = 49.5, average 16.5.
  • strip() removed the spaces around 30, which Double.parseDouble also tolerates, but a value such as "30 kg" would still throw NumberFormatException.
  • Before Java 25 the same program needed a Scanner or a BufferedReader on System.in; see Scanner and Console.

What the implicit class looks like

A compact source file can inspect itself with reflection, which confirms the description at the top. It also uses an explicit import, which is still allowed, and an instance field.

Java
import java.lang.reflect.Modifier;   // explicit imports are still allowed

// A compact source file can still use reflection on itself
int calls = 0;

void main() {
    calls++;
    Class<?> c = getClass();
    IO.println("name:        " + c.getName());
    IO.println("package:     \"" + c.getPackageName() + "\"");
    IO.println("modifiers:   " + Modifier.toString(c.getModifiers()));
    IO.println("superclass:  " + c.getSuperclass().getSimpleName());
    IO.println("constructor: " + c.getDeclaredConstructors().length + " (generated)");
    IO.println("field calls: " + calls + ", an instance field of the implicit class");
    IO.println("java.base imported: " + new ArrayList<>(List.of(LocalDate.of(2026, 1, 1))));
}

Output:

Output
name:        Inspect
package:     ""
modifiers:   final
superclass:  Object
constructor: 1 (generated)
field calls: 1, an instance field of the implicit class
java.base imported: [2026-01-01]

The class is named Inspect, its package name is the empty string, its only modifier is final, it extends Object, and it has exactly one constructor, the generated one. calls is an instance field, which works because the launcher created an instance before calling main. ArrayList, List and LocalDate came from the automatic java.base import.

Which main method the launcher picks

The relaxed rules apply to ordinary classes as well. When a class declares more than one candidate, the launcher chooses in this order:

  1. a main(String[]) method that is public, protected or package-private, static or not;
  2. otherwise, a main() with no parameters, static or not.

The class below has both instance forms, to see which one wins:

Java
// When a class has more than one candidate, the launcher prefers main(String[]) over main()
class WhichMain {

    void main() {
        System.out.println("instance main() with no parameters");
    }

    void main(String[] args) {
        System.out.println("instance main(String[]) chosen, args = " + args.length);
    }
}

Output:

Output
instance main(String[]) chosen, args = 0

The version with String[] won and received 0 arguments, so existing programs keep their behaviour. A private main is never chosen. If the chosen main is an instance method, the class needs a non-private constructor without parameters, or the launcher fails before running anything.

What the compiler rejects

The program compiles seven small compact source files in memory, each named Demo.java, and prints javac's verdict.

Java
import java.net.URI;
import java.util.List;
import java.util.Locale;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;

// Compiles small compact source files in memory and prints javac's verdict
public class CompactRules {

    public static void main(String[] args) {
        check("a statement outside any method", "IO.println(\"hi\");");
        check("a package declaration", "package demo;\nvoid main() { }");
        check("a constructor", "Demo() { }\nvoid main() { }");
        check("no main method", "void run() { }");
        check("an ambiguous name from java.base", "void main() { Proxy p = null; }");
        check("the ambiguity resolved by an import",
                "import java.net.Proxy;\nvoid main() { Proxy p = Proxy.NO_PROXY; }");
        check("a static main and helper", "static void main() { help(); }\nstatic void help() { }");
    }

    static void check(String label, String source) {
        JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
        DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<>();
        JavaFileObject file = new SimpleJavaFileObject(
                URI.create("string:///Demo.java"), JavaFileObject.Kind.SOURCE) {
            @Override
            public CharSequence getCharContent(boolean ignoreEncodingErrors) {
                return source;
            }
        };
        boolean ok = javac.getTask(null, null, diags,
                List.of("-d", System.getProperty("java.io.tmpdir")), null, List.of(file)).call();
        System.out.println(label + ": " + (ok ? "compiles" : ""));
        for (Diagnostic<? extends JavaFileObject> d : diags.getDiagnostics()) {
            String text = d.getMessage(Locale.ENGLISH).strip();
            System.out.println("  error: " + String.join(" ", text.split("\\s*\\n\\s*")));
        }
    }
}

Output:

Output
a statement outside any method: 
  error: class, interface, annotation type, enum, record, method or field expected
a package declaration: 
  error: compact source file should not have package declaration
a constructor: 
  error: invalid method declaration; return type required
no main method: 
  error: compact source file does not have main method in the form of void main() or void main(String[] args)
an ambiguous name from java.base: 
  error: reference to Proxy is ambiguous both class java.net.Proxy in java.net and class java.lang.reflect.Proxy in java.lang.reflect match
the ambiguity resolved by an import: compiles
a static main and helper: compiles
  • Statements must still be inside a method: a bare IO.println("hi"); at the top level is an error. A compact file is a class body without the header, not a script.
  • A package declaration is not allowed, because the implicit class always lives in the unnamed package.
  • A constructor cannot be declared: Demo() { } looks like a method with no return type, since the class has no name you can write. Put setup code in field initializers or at the start of main.
  • A compact file must have a main, in the form void main() or void main(String[] args).
  • The trap in the automatic import: Proxy exists in both java.net and java.lang.reflect, so using the simple name is ambiguous. An explicit single-type import, import java.net.Proxy;, takes priority over the module import and fixes it.
  • A static main with static helpers is also fine.

Running files straight from source

Compact source files are most useful together with the source launcher, which compiles a file in memory and runs it in one step. The program writes two files into a temporary directory and starts a separate java Greet.java hello world process, as you would from a terminal.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

// Runs compact source files with "java File.java", the way you would from a terminal
public class SourceLauncher {

    public static void main(String[] args) throws IOException, InterruptedException {
        Path dir = Files.createTempDirectory("scripts");
        Files.writeString(dir.resolve("Greet.java"), """
                void main(String[] args) {
                    IO.println("args: " + String.join(", ", args));
                    IO.println(Helper.shout(args[0]));
                }
                """);
        // A second file in the same directory: found automatically since Java 22
        Files.writeString(dir.resolve("Helper.java"), """
                class Helper {
                    static String shout(String s) { return s.toUpperCase() + "!"; }
                }
                """);
        run(dir, "Greet.java", "hello", "world");
        System.out.println("class files written: " + listClassFiles(dir));
    }

    static void run(Path dir, String... command) throws IOException, InterruptedException {
        String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
        ProcessBuilder pb = new ProcessBuilder();
        pb.command().add(java);
        pb.command().addAll(List.of(command));
        pb.directory(dir.toFile()).redirectErrorStream(true);
        pb.environment().remove("JAVA_TOOL_OPTIONS");
        Process p = pb.start();
        System.out.print(new String(p.getInputStream().readAllBytes()));
        System.out.println("exit code " + p.waitFor());
    }

    static long listClassFiles(Path dir) throws IOException {
        try (var files = Files.list(dir)) {
            return files.filter(f -> f.toString().endsWith(".class")).count();
        }
    }
}

Output:

Output
args: hello, world
HELLO!
exit code 0
class files written: 0
  • The arguments after the file name reached main(String[] args) as "hello" and "world".
  • Greet.java used the class Helper from a second file in the same directory. The launcher has found such files on demand since Java 22 (JEP 458); with Java 11 to 21, a source-launched program had to fit in one file.
  • No .class files were written: the launcher compiles into memory. For a program run many times, compiling once with javac starts faster.

When to use a compact source file

Compact source file or ordinary class
SituationUse
A script, a small tool, an experimentCompact source file, run with java File.java
Teaching the first steps of JavaCompact source file with IO.println and IO.readln
Code that other classes must refer to by nameAn ordinary class
Code that belongs in a package or a moduleAn ordinary class
Need a constructor with parametersAn ordinary class
Must run on JDK 24 or olderAn ordinary class with public static void main(String[] args)

Converting later is mechanical: wrap the file's contents in class Name { ... }, add imports for what the automatic java.base import supplied, and the methods inside do not change.