Compact source files and instance main methods

suggest change

Since Java 25 (JEP 512, final) this is a complete Java program:

void main() {
    IO.println("Hello, World!");
}

Save it as Hello.java and run it:

$ java Hello.java
Hello, World!

Compare it with the classic version in Creating Your First Java Program: there's no public class, no static, no String[] args and no System.out. Two features make this work:

Both are also helped by a new class, java.lang.IO, with simple console methods, and by an automatic import module java.base; in compact source files.

The features went through four previews (JEP 445 in Java 21 as "unnamed classes and instance main methods", then JEPs 463, 477 and 495) before becoming final in Java 25. You don't need --enable-preview anymore, but the code requires --release 25 or newer:

$ javac --release 21 Hello.java
Hello.java:1: error: implicitly declared classes are not supported in -source 21
void main() {
^
  (use -source 25 or higher to enable implicitly declared classes)
1 error

A compact source file is a class

A compact source file is still compiled into an ordinary class. You can run it directly with the source launcher (java Hello.java) or compile it first:

$ javac Hello.java
$ java Hello
Hello, World!
$ javap -p Hello.class
Compiled from "Hello.java"
final class Hello {
  Hello();
  void main();
}

The compiler created an implicitly declared class:

You can use everything you could use in a normal class body: fields with initializers, helper methods, static members, and nested classes, records, enums and interfaces.

final List<String> words = new ArrayList<>();

void main() {
    add("banana"); add("apple"); add("cherry"); add("apple");
    Map<String, Long> counts = words.stream()
        .collect(Collectors.groupingBy(w -> w, TreeMap::new, Collectors.counting()));
    IO.println(counts);
    IO.println("total: " + words.size() + ", today: " + LocalDate.of(2026, 10, 18).getDayOfWeek());
}

void add(String w) {
    words.add(w);
}

record Point(int x, int y) {}
{apple=2, banana=1, cherry=1}
total: 4, today: SUNDAY

List, ArrayList, Map, TreeMap, Collectors and LocalDate were used without a single import (more on that below). words is an instance field, and add is an instance method called from the instance method main. record Point becomes the nested class Words$Point.

Static and instance state mix as usual, and nested (inner) classes can see the fields of the implicit class:

static int instances = 0;
int count = 0;

void main() {
    instances++;
    bump(); bump(); bump();
    IO.println("count=" + count + " instances=" + instances);
    IO.println(new Helper().describe());
}

void bump() { count++; }

class Helper {
    String describe() { return "inner class sees count=" + count; }
}
count=3 instances=1
inner class sees count=3

What a compact source file can't do

Because the class has no declared name, some things are not allowed:

Instance main methods

The new rules for main are not limited to compact source files. Any class can use them. The launcher accepts a main method that:

If main is an instance method, the launcher creates an object with the class's non-private no-argument constructor and then calls main on it:

public class App {
    private final String greeting;

    App() {
        greeting = "constructed by the launcher";
        IO.println("App() called");
    }

    void main() {
        IO.println(greeting);
    }
}
$ java App.java
App() called
constructed by the launcher

If there's no such constructor, the class compiles fine but can't be launched:

class NoCtor {
    NoCtor(int x) {}
    void main() { IO.println("hi"); }
}
$ javac NoCtor.java
$ java NoCtor
Error: no non-private zero argument constructor found in class NoCtor
remove private from existing constructor or define as:
   public NoCtor()

main can also be inherited from a superclass, which lets a base class define a common entry point:

public class Base extends Tool {
    String name() { return "Base"; }
}

abstract class Tool {
    void main(String[] args) {
        IO.println(name() + " running with " + args.length + " args");
    }
    abstract String name();
}
$ javac -d out Base.java
$ java -cp out Base a b
Base running with 2 args

Compile this one with javac. In source-file mode (java Base.java) the launcher runs the first top-level class in the file that declares a main method, which here is the abstract Tool, and fails with error: abstract class: Tool can not be instantiated.

Which main is chosen

A class can have more than one candidate, for example a main() and a main(String[]). The launcher picks in this order:

  1. a main(String[] args) method, static or instance, declared in the class or inherited
  2. otherwise, a main() method with no parameters, static or instance

So the String[] version always wins, regardless of static:

void main() {
    IO.println("main()");
}

void main(String[] args) {
    IO.println("main(String[])");
}
main(String[])
class Static {
    static void main() { IO.println("static main()"); }
    void main(String[] args) { IO.println("instance main(String[])"); }
}
instance main(String[])

Avoid relying on this: give a class one main method. The rules exist so that old classes with public static void main(String[] args) keep working exactly as before.

Command line arguments

Declare String[] args when you need arguments, and leave it out when you don't:

void main(String[] args) {
    String name = args.length > 0 ? args[0] : "stranger";
    IO.println("Hello, " + name + "!");
    IO.println("this class: " + getClass().getName());
}
$ java Greet.java Alice
Hello, Alice!
this class: Greet

Since main is an instance method, this and getClass() work inside it.

Console I/O with java.lang.IO

System.out.println makes beginners learn about classes, static fields and PrintStream before they can print a line, and reading a line needs a BufferedReader around InputStreamReader(System.in) or a Scanner. Java 25 adds java.lang.IO, a final class with five static methods:

Method What it does
IO.println(Object obj) prints obj (via String.valueOf, so null prints null) and a line separator
IO.println() prints a line separator
IO.print(Object obj) prints obj without a line separator
IO.readln() reads one line from standard input; returns null at end of input
IO.readln(String prompt) prints the prompt, then reads one line

IO is in java.lang, so it is available in every Java file, not just compact source files. The methods are not imported statically: you must write IO.println, not println. (Some of the preview versions in Java 23 and 24 imported them automatically. The final version dropped that.)

void main() {
    String name = IO.readln("What is your name? ");
    int age = Integer.parseInt(IO.readln("How old are you? "));
    IO.print("Hi " + name + ", ");
    IO.println("next year you'll be " + (age + 1) + ".");
    IO.println();
    String line;
    int n = 0;
    while ((line = IO.readln()) != null) {
        n += line.length();
    }
    IO.println("characters in the rest of input: " + n);
}

With input piped in (so the typed answers don't appear on screen):

$ printf 'Ada\n36\nfoo\nbarbaz\n' | java Ask.java
What is your name? How old are you? Hi Ada, next year you'll be 37.

characters in the rest of input: 9

IO is intentionally minimal. There's no printf; use IO.println(String.format(...)) or "...".formatted(...), or System.out.printf. readln returns a String, so parse numbers yourself. System.out and System.in remain the right tools for anything more involved.

The implicit import of java.base

Every compact source file behaves as if it started with:

import module java.base;

A module import declaration (JEP 511, also final in Java 25) imports all public top-level types of all packages exported by a module. java.base exports java.util, java.util.function, java.util.stream, java.io, java.nio.file, java.math, java.time, java.net, java.util.concurrent and about 50 more packages. That's why the examples above can use List, Files, Path and LocalDate with no imports.

Types from other modules still need imports. JFrame is in the java.desktop module:

Swing.java:2: error: cannot find symbol
    var f = new JFrame("x");
                ^
  symbol:   class JFrame
  location: class Swing

You can add normal import statements (single type, on-demand, import static or another import module) at the top of a compact source file. When two imported modules export a type with the same simple name, a single-type import settles the ambiguity. java.desktop has java.awt.List and java.base has java.util.List:

import module java.desktop;
import java.util.List;   // without this line, "reference to List is ambiguous"

void main() {
    IO.println(JFrame.class.getModule());
    List<String> l = List.of("a");
    IO.println(l);
}
module java.desktop
[a]

Normal (explicitly declared) classes don't get the automatic import. They can write import module java.base; themselves, as shown in the next section.

Growing a script into a program

Compact source files are good for small tools, experiments and learning. Here's a script that prints the most frequent words in a file:

final Map<String, Integer> counts = new HashMap<>();

void main(String[] args) throws IOException {
    int limit = args.length > 1 ? Integer.parseInt(args[1]) : 3;
    for (String line : Files.readAllLines(Path.of(args[0]))) {
        countWords(line);
    }
    counts.entrySet().stream()
        .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()
            .thenComparing(Map.Entry.comparingByKey()))
        .limit(limit)
        .forEach(e -> IO.println(e.getKey() + " " + e.getValue()));
}

void countWords(String line) {
    for (String w : line.toLowerCase().split("[^a-z]+")) {
        if (!w.isEmpty()) counts.merge(w, 1, Integer::sum);
    }
}
$ cat text.txt
the quick brown fox
jumps over the lazy dog
the end
$ java TopWords.java text.txt 2
the 3
brown 1

When it needs to live in a package, be used from other classes or be tested, turn it into a normal class. The minimal change is to wrap the members in a class declaration and add a package and the import that used to be implicit:

package com.example.words;

import module java.base;

public class TopWords {
    private final Map<String, Integer> counts = new HashMap<>();

    void main(String[] args) throws IOException {
        int limit = args.length > 1 ? Integer.parseInt(args[1]) : 3;
        for (String line : Files.readAllLines(Path.of(args[0]))) {
            countWords(line);
        }
        counts.entrySet().stream()
            .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()
                .thenComparing(Map.Entry.comparingByKey()))
            .limit(limit)
            .forEach(e -> IO.println(e.getKey() + " " + e.getValue()));
    }

    void countWords(String line) {
        for (String w : line.toLowerCase().split("[^a-z]+")) {
            if (!w.isEmpty()) counts.merge(w, 1, Integer::sum);
        }
    }
}
$ javac -d out src/com/example/words/TopWords.java
$ java -cp out com.example.words.TopWords text.txt 4
the 3
brown 1
dog 1
end 1

The body of the class is unchanged: main stays an instance method and IO.println still works. If the code must also compile on Java 21 or earlier, go all the way to the traditional form: public static void main(String[] args) that creates an instance (new TopWords()) and calls its methods, explicit single-type imports such as import java.util.Map;, and System.out.println instead of IO.println.

Many projects keep a static main in their entry class for that reason, and because frameworks and tools that look up main by reflection may still expect public static void main(String[]).

Where else it fits

Summary

Feedback about page:

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



Table Of Contents