Compact source files and instance main methods
suggest changeSince 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:
- Compact source files: a
.javafile can contain methods and fields at the top level, without a class around them. The compiler wraps them in a class for you. - Instance main methods:
mainno longer has to bepublic static void main(String[] args). It can be an instance method, and theString[] argsparameter is optional.
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:
- its name comes from the file name, so the file name must be a valid Java identifier (
hello-world.javafails witherror: bad file name: hello-world) - it is
final, package-private and in the unnamed package - it extends
Objectand has a default no-argument constructor - top-level methods become its instance methods (or static ones, if you mark them
static) and top-level variables become its fields
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:
-
No
packagedeclaration. The class is always in the unnamed package:Pkg.java:1: error: compact source file should not have package declaration package demo; ^ -
No referring to the class by name. Code in the file (and other files) can't write
new Ref()orRef.someStaticMethod(). Inside the file, usethisor just call the methods directly. As a result, a compact source file is a program entry point, not a reusable library class.Ref.java:2: error: cannot find symbol class Other { int x() { return new Ref().hashCode() > 0 ? 1 : 0; } } ^ symbol: class Ref -
It must have a launchable
mainmethod. A file of top-level methods withoutmainis an error, even if you only compile it:NoMain.java:1: error: compact source file does not have main method in the form of void main() or void main(String[] args) void hello() { IO.println("hi"); } ^A
privatemain method doesn't count and produces the same error. -
No statements at the top level. This is not a scripting language with loose statements; code still lives in methods:
Stmt.java:1: error: class, interface, annotation type, enum, record, method or field expected IO.println("top-level statement"); ^
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:
- returns
void - takes either
String[]or no parameters - is not
private(it can bepublic,protectedor package-private) - can be
staticor an instance method
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:
- a
main(String[] args)method, static or instance, declared in the class or inherited - 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
- JShell already allowed top-level methods and statements.
IO.printlnworks there too; see JShell. A compact source file is a good next step when a JShell session grows: copy the methods into a file and addvoid main(). - Source launcher:
java File.javacompiles in memory and runs, so a compact source file is a single-file script with no build step. See Java command: java and javaw. - Teaching: the first program can be
void main() { IO.println("Hello"); }, andstatic,public, arrays and classes can be introduced later. See Getting started with Java Language.
Summary
- A compact source file contains top-level fields and methods; the compiler wraps them in a
finalimplicitly declared class named after the file, in the unnamed package. - It must have a non-private
void main()orvoid main(String[] args), can't have apackagedeclaration, and its class can't be referenced by name. - Any class can now use an instance
mainand dropString[] args. The launcher instantiates the class with its no-argument constructor.main(String[])is preferred overmain(). java.lang.IOprovidesprintln,printandreadln. Call them asIO.println(...).- Compact source files implicitly
import module java.base;, so most of the standard library needs no imports. - To grow a script, wrap it in a class, add a
packageandimport module java.base;(or explicit imports), and keep or convertmainas needed.