Java 25 makes it official: you can now write and run a program without declaring a class, without public static void main(String[] args), and even without import statements for common APIs. This feature is called Compact Source Files and Instance Main Methods (JEP 512, finalized in Java 25).
Let’s walk through it step by step.
1. Prerequisites
- JDK 25 installed and available on your
PATH - Verify with:
java --version
javac --version
Both should report version 25.
2. Write the Program
Create a plain text file named Hello.java. That’s it — no class, no public static, no ceremony:
void main() {
IO.println("Hello, Java 25!");
}
A few things worth noticing:
- There is no class declaration. The compiler wraps the code in an implicitly declared class for you.
mainis an instance method (notstatic) and takes no arguments (theString[] argsparameter is optional now).IO.println(...)comes from the newjava.io.IOclass, which is auto-imported in compact source files — noSystem.out.printlnand noimportneeded.
3. Run It Directly with java
Since JDK 11, you can run a single-file source program directly. In Java 25, this works beautifully with the new compact form:
java Hello.java
Expected output:
Hello, Java 25!
No javac step is required. The launcher compiles the file in memory and runs it.
4. A Slightly Richer Example
You can still read input, do logic, and use any Java API — just without the boilerplate:
void main() {
var name = IO.readln("What is your name? ");
IO.println("Welcome, " + name + "!");
for (int i = 1; i <= 3; i++) {
IO.println("Count: " + i);
}
}
Run it the same way:
java Hello.java
5. When You Outgrow It
Compact source files are meant for learning, scripting, and quick experiments. When your program grows, you can gradually add:
- A
String[] argsparameter tomainwhen you need CLI arguments. - Additional methods and fields directly in the file (they become members of the implicit class).
- Finally, an explicit
classdeclaration — at which point you have a regular Java source file.
The transition is smooth because the language rules are a strict superset of traditional Java.
6. Common Pitfalls
| Issue | Cause | Fix |
|---|---|---|
error: class ... is public, should be declared in a file named ... |
You added public to a helper class in the same file |
Remove public — the implicit class is unnamed |
IO cannot be resolved |
You’re not on JDK 25 (or using an older preview flag) | Upgrade to JDK 25; no --enable-preview needed anymore |
main not found |
Wrong signature (e.g., returns int) |
Use void main() or void main(String[] args) |
Summary
To run your first Java 25 program without creating a class:
- Install JDK 25.
- Create
Hello.javacontaining just avoid main()method. - Use
IO.println(...)— no imports needed. - Run it with
java Hello.java.
This is the shortest path from “I have JDK installed” to “my program is running” that Java has ever offered — perfect for beginners and for quick prototypes alike.
