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 smallest program Fields, methods, records and automatic imports Reading console input with IO.readln What the implicit class looks like Which main method the launcher picks What the compiler rejects Running files straight from source When to use a compact source file
What a compact source file is
The classic first Java program needs public classpublic static void main(String[] args)System.out.println
- Compact source files. A
file may contain methods and fields with no enclosing class. The compiler wraps them in an implicitly declared class: it is.java , extendsfinal , 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.Object - Instance main methods. The launcher accepts a
that is notmain , notpublic , and takes no parameters. For an instance method, it creates an object with the no-argument constructor first and then callsstatic on it.main
A compact source file also imports every exported package of the java.baseimport module java.base;java.utiljava.util.streamjava.iojava.nio.filejava.timejava.lang.IOprintlnprintreadlnSystem.outScanner
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 { ... }
| JDK | JEP | Name and status |
|---|---|---|
| 11 | JEP 330 | Launch single-file source programs: java Hello.java |
| 21 | JEP 445 | Unnamed Classes and Instance Main Methods (preview) |
| 22 | JEP 463, JEP 458 | Implicitly Declared Classes (second preview); multi-file source programs (standard) |
| 23 | JEP 477 | Third preview: automatic import of java.baseIO |
| 24 | JEP 495 | Simple Source Files and Instance Main Methods (fourth preview) |
| 25 | JEP 512 | Compact Source Files and Instance Main Methods (standard); IOjava.lang |
On JDK 21 to 24 such files compile only with --enable-preview --release Njavac Hello.java
The smallest program
This is the whole content of Hello.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.javajavac Hello.javajava Hello
Hello from a compact source file
Running on Java 25
IO.printlnSystem.out.printlnRuntime.version().feature()IOjava.langjava.base
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
// 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:
words: 10
the x3
dog x1
end x1
class name chosen by javac: WordStats
- No import statements were written for
,List ,Map ,TreeMap ,Arrays orComparator .Collectors - "the" is first with 3. The other two places are a tie at 1. The counts were collected into a
, so the tied words start in alphabetical order, and becauseTreeMap is stable, "dog" and "end" won the tie.sorted printedgetClass().getName() : 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.WordStats- The record
became a nested class,WordCount in the compiled output.WordStats$WordCount
Reading console input with IO.readln
IO.readln(prompt)null127.5 30 99
// 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):
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.
removed the spaces around 30, whichstrip() also tolerates, but a value such asDouble.parseDouble would still throw"30 kg" .NumberFormatException- Before Java 25 the same program needed a
or aScanner onBufferedReader ; seeSystem.inScanner 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.
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:
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 InspectfinalObjectcallsmainArrayListListLocalDatejava.base
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:
- a
method that ismain(String[]) ,public or package-private, static or not;protected - otherwise, a
with no parameters, static or not.main()
The class below has both instance forms, to see which one wins:
// 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:
instance main(String[]) chosen, args = 0
The version with String[]privatemainmain
What the compiler rejects
The program compiles seven small compact source files in memory, each named Demo.javajavac
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:
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
at the top level is an error. A compact file is a class body without the header, not a script.IO.println("hi"); - A package declaration is not allowed, because the implicit class always lives in the unnamed package.
- A constructor cannot be declared:
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 ofDemo() { } .main - A compact file must have a
, in the formmain orvoid main() .void main(String[] args) - The trap in the automatic import:
exists in bothProxy andjava.net , so using the simple name is ambiguous. An explicit single-type import,java.lang.reflect , takes priority over the module import and fixes it.import java.net.Proxy; - A
static with static helpers is also fine.main
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
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:
args: hello, world
HELLO!
exit code 0
class files written: 0
- The arguments after the file name reached
as "hello" and "world".main(String[] args) used the classGreet.java 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.Helper- No
files were written: the launcher compiles into memory. For a program run many times, compiling once with.class starts faster.javac
When to use a compact source file
| Situation | Use |
|---|---|
| A script, a small tool, an experiment | Compact source file, run with java File.java |
| Teaching the first steps of Java | Compact source file with IO.printlnIO.readln |
| Code that other classes must refer to by name | An ordinary class |
| Code that belongs in a package or a module | An ordinary class |
| Need a constructor with parameters | An ordinary class |
| Must run on JDK 24 or older | An ordinary class with public static void main(String[] args) |
Converting later is mechanical: wrap the file's contents in class Name { ... }java.base