Compact Source Files and Instance Main Methods in Java 25
A compact source file is a .java file whose methods and fields are written without a class declaration. The compiler wraps them in an implicitly declared class, and the main method can be a plain instance method: no public, no static, and no String[] args parameter. The feature became standard in Java 25 (JEP 512), together with the new class java.lang.IO for simple console input and output.
// File Hello.java is the whole program
void main() {
IO.println("Hello, World!");
} java Hello.java
Hello, World! The classic version from How to Write Your First Java Application has not gone anywhere: public static void main(String[] args) still works and appears in every real-world project. Compact source files are meant for first programs, scripts and quick experiments. Below are the exact rules: what such a file may contain, which classes are available without imports, and which main the JVM picks when there are several.
1. Compact source files: a first program without a class
In a regular .java file, only type declarations may appear at the top level: classes, interfaces, enums and records. When the compiler finds a method or a field at the top level, it treats the file as a compact source file and declares the class itself. You run such a program the same two ways as any other (see Compile and Run Java Applications from the Command Line):
# 1. Straight from the source, no .class file
java Hello.java
# 2. The classic way: compile, then run
javac Hello.java
java Hello In the second case javac produces an ordinary Hello.class file: the name of the implicit class comes from the file name.
The feature went through four preview rounds, and the rules changed between them. This matters when you run into an older article or example:
| Java version | JEP | Status and what changed |
|---|---|---|
| 21 | JEP 445 | Preview: "unnamed classes" and instance main methods |
| 22 | JEP 463 | Second preview: renamed to "implicitly declared classes" |
| 23 | JEP 477 | Third preview: class java.io.IO with its methods statically imported, automatic import of the java.base module |
| 24 | JEP 495 | Fourth preview, no significant changes |
| 25 | JEP 512 | Final: the class moved to java.lang.IO, its methods are no longer statically imported, so you write IO.println() |
In Java 21–24 this code worked only with the --enable-preview flag (plus --release N for javac). From Java 25 on, no flags are needed.
2. Implicitly declared classes: the rules
A compact source file can contain fields, methods and even nested types. They all become members of the implicit class, so methods see the fields and each other, and this is available inside instance methods:
// File Greeter.java
String greeting = "Hello";
String greet(String name) {
return greeting + ", " + name + "!";
}
void main() {
List<String> names = List.of("Anna", "Boris");
for (String n : names) {
IO.println(greet(n));
}
IO.println(getClass().getName());
IO.println(java.lang.reflect.Modifier.toString(getClass().getModifiers()));
IO.println(getClass().getPackageName().isEmpty());
}
// Hello, Anna!
// Hello, Boris!
// Greeter
// final
// true Note that List is used without an import; the next section explains why. The last three lines of output show the key properties of an implicit class:
| Property of the implicit class | Consequence |
|---|---|
| Its name comes from the file name | Greeter.java → class Greeter, file Greeter.class |
The class is final | It cannot be extended |
| It lives in the unnamed package | A package declaration in a compact file is a compile error (packages are covered in Understanding Java Packages) |
| It cannot be referenced by name | Even inside the same file, new Greeter() does not compile: cannot find symbol |
| Only the default constructor | You cannot declare a constructor: there is no class name to write |
Extends Object, no implements | There is no class header, so there is nowhere to name a superclass or interfaces |
Must have a launchable main | Otherwise javac reports: compact source file does not have main method in the form of void main() or void main(String[] args) |
Code outside methods is still not allowed. A compact source file is "a class body without a header", not a script with top-level statements:
// File TopStmt.java: compile error
IO.println("x");
// error: class, interface, annotation type, enum, record, method or field expected You can declare nested classes and records; they become members of the implicit class. The full name shows it:
// File Helper.java
void main() {
IO.println(new Helper().hi());
}
class Helper {
String hi() {
return "helper is " + getClass().getName();
}
}
// helper is Helper$Helper Here Helper is an inner class of the implicit class Helper (the file name), hence Helper$Helper. That is why you can create it only from instance methods: in static void main() the line new Helper() does not compile (non-static variable this cannot be referenced from a static context).
3. Automatic import of the java.base module
A compact source file behaves as if it started with import module java.base;. Without a single import, all public classes and interfaces from the packages exported by the java.base module are available: java.util, java.io, java.nio.file, java.math, java.time, java.util.function, java.util.stream, java.util.concurrent and others.
// File Imports.java: no imports at all
void main() {
Path p = Path.of("a.txt"); // java.nio.file
Map<String, Integer> m = new HashMap<>(); // java.util
Function<Integer, Integer> f = x -> x * 2; // java.util.function
IO.println(p + " " + m + " " + f.apply(21));
}
// a.txt {} 42 Three details that are often tested:
- Only
java.base. Classes from other modules, such asjava.sql.Connection(modulejava.sql) orjavax.swing.JFrame(modulejava.desktop), must be imported explicitly. That is whyDatein a compact file meansjava.util.Date, with no clash withjava.sql.Date. - Explicit imports are allowed. Regular
importandimport staticdeclarations can go at the top of a compact file, as in any other file. - The rule applies to compact files only. In a normal class only
java.langis imported automatically, as before.
// File ExplicitImp.java
import static java.lang.Math.*;
void main() {
IO.println(max(2, 3) + " " + PI);
}
// 3 3.141592653589793 4. The java.lang.IO class: print, println, readln
java.lang.IO is a final class with static methods for console input and output. It lives in the java.lang package, so it is available in any Java 25 file, not only in compact ones.
| Method | What it does |
|---|---|
static void print(Object obj) | Prints a value without a line break |
static void println(Object obj) | Prints a value and ends the line |
static void println() | Ends the line only |
static String readln() | Reads a line from the console; returns null at end of input |
static String readln(String prompt) | Prints a prompt, then reads a line |
// File Read.java
void main() {
String name = IO.readln("Name: ");
IO.println("Hi, " + name);
}
// Name: Tanya
// Hi, Tanya The IO methods are not statically imported: you must write IO.println("x"). A bare println("x") does not compile (cannot find symbol). That shortcut existed only in the Java 23–24 previews.
IO has no printf and no readInt: readln() returns a string, and you get a number from it with Integer.parseInt(). Internally IO works on top of System.out and System.in, so System.setOut() redirects IO.println() as well. The standard streams, printf() and System.err are covered in Java Standard Streams: System.in, System.out and System.err.
5. Instance main methods and how main is selected
JEP 512 changed not only the file syntax but also the launch protocol. The JVM now accepts four forms of main, and in any class, not only an implicit one:
public static void main(String[] args) // classic
static void main() // static, no parameters
void main(String[] args) // instance method with arguments
void main() // instance method, no parameters Requirements: the return type is void, and any access modifier except private is fine (public, protected or package access). The launcher does not see private void main() and reports Main method not found.
If several methods qualify, the launcher chooses like this:
- First it looks for
main(String[] args), static or instance. - If there is none, it looks for
main()with no parameters. - If the chosen method is static, it is called directly. If it is an instance method, the JVM creates an object through a non-private no-argument constructor and calls the method on it.
What decides is the String[] parameter, not static:
// File Priority.java
static void main() {
IO.println("static main()");
}
void main(String[] args) {
IO.println("instance main(String[])");
}
// instance main(String[]) A static and an instance main with the same parameters cannot coexist: it is the same signature, and javac reports method main(String[]) is already defined.
Instance main methods work in a normal class too, even a non-public one:
// File App.java
public class App {
void main() {
IO.println("instance main in a normal class");
}
}
// java App.java → instance main in a normal class New launch errors, which did not exist before Java 25, appear when the object cannot be created:
public class PrivCtor {
private PrivCtor() { }
void main() { IO.println("ok"); }
}
// Error: no non-private zero argument constructor found in class PrivCtor
public abstract class Abstract {
void main() { IO.println("x"); }
}
// Error: abstract class Abstract can not be instantiated Both programs compile; the error comes from the java launcher at run time. An inherited main, on the other hand, qualifies: if class Inherit extends Base has no method of its own, the JVM calls Base.main() on an Inherit object. If the program needs command-line arguments, keep the String[] args parameter; see Command-Line Arguments in Java.
6. Does it compile? Typical cases
Each row below is a separate file. Results were obtained on JDK 25.
| File contents | Result | Why |
|---|---|---|
void main() { IO.println("x"); } | Compiles, prints x | The smallest compact source file |
void main() { println("x"); } | Compile error | IO methods are not statically imported |
int main() { return 0; } | Compile error | main must return void |
void hello() { } | Compile error | The compact file has no launchable main |
package demo; + void main() { } | Compile error | An implicit class is always in the unnamed package |
Greeter() { } + void main() { } | Compile error | You cannot declare a constructor |
class P { private void main() { } } | Compiles, but java P fails | The launcher does not see a private main |
class Q { protected static void main() { } } | Compiles and runs | Any access except private works |
static void main() + void main(String[] a) | main(String[]) runs | The method with the parameter wins |
7. Turning a compact file into a normal class
When the program grows, converting it to a normal class is easy: wrap the contents in a class declaration named after the file and add the imports that used to be implicit. The main method does not have to change.
// Before: Greeter.java (compact source file)
String greet(String name) { return "Hello, " + name; }
void main() { IO.println(greet("Anna")); }
// After: Greeter.java (normal class)
import java.util.*; // explicit imports for everything that used to come from java.base
class Greeter {
String greet(String name) { return "Hello, " + name; }
void main() { IO.println(greet("Anna")); }
} Which syntax to use
Compact source files and instance main methods are handy for learning, scripts and testing an idea in a minute. In production projects, classes live in packages, and the entry point is almost always public static void main(String[] args), which every Java version, framework and build tool supports. The rest of this course uses the classic syntax.
Frequently asked questions
Since which Java version can I write void main() without a class?
As a standard feature, since Java 25 (JEP 512). In Java 21–24 it was a preview feature that required the --enable-preview flag, and in Java 23–24 println could be called without the IO prefix. That no longer works in Java 25: you write IO.println().
Will void main() replace public static void main(String[] args)?
No. The classic form keeps working and is required for programs that must run on Java 24 and earlier. The new forms are a simplification for beginners and small programs. If a class has both forms, with and without the parameter, the launcher chooses main(String[] args).
What is the difference between IO.println() and System.out.println()?
The result is the same: IO.println() writes to System.out. The difference is convenience: the name is shorter, and IO.readln("Name: ") reads a line with a prompt without Scanner or BufferedReader. For formatting (printf) and error output (System.err) you still need the standard streams.
Can another class use an implicitly declared class?
No. An implicit class has no name you can refer to in code: even inside the same file, new Greeter() does not compile. An implicit class is always a standalone runnable program. If the code needs to be reused, make it a normal class in a package.
Why does an instance main fail with "no non-private zero argument constructor"?
To call an instance method, the JVM first creates an object through a no-argument constructor that is not private. If the class has only a private constructor or only constructors with parameters, the object cannot be created. The code still compiles; the error appears only at launch. Add a non-private no-argument constructor or make main static.
Comments