Compact Source Files & Instance Main Methods (JEP 512)
NOTE: This feature, formerly known as Implicitly Declared Classes and Instance Main Methods, is finalized in Java 25.
One of the biggest hurdles for beginners learning Java has always been the boilerplate code. To write a simple “Hello, World!”, you needed a public class, a static main method, and an array of Strings argument that you probably wouldn’t use.
Java 25 changes this with Compact Source Files (JEP 512). This feature allows you to write Java programs that are more concise and script-like, without sacrificing the power of the language.
The Old Way
Remember this?
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
For a newcomer, this is a lot to digest. What is public? What is static? Why String[] args?
The New Way (Java 25)
With Java 25, you can simply write:
void main() {
System.out.println("Hello, World!");
}
That’s it! No class declaration, no public, no static, and no String[] args if you don’t need them.
How it works
Behind the scenes, the Java compiler treats this as if it were inside an implicitly declared class.
- Instance Main Methods: The
mainmethod no longer needs to bestatic. It can be an instance method. - No Access Modifiers: You don’t strict need
publicorprotected. - Implicit Class: If your source file doesn’t have an outer class declaration, the compiler automatically wraps your methods and fields in a class.
Fields and Methods
You can also define fields and other methods just like you would in a normal class:
String greeting = "Hello, Java 25!";
void main() {
System.out.println(greeting);
greetUser("Developer");
}
void greetUser(String name) {
System.out.println("Welcome, " + name);
}
This makes Java feel much more like a scripting language for small programs, while still being full-fledged Java.
Why is this important?
- Beginner Friendly: Reduces concepts needed to write the first program.
- Less Boilerplate: clearer code for small utilities and scripts.
- Gradual Complexity: You can start with a simple method and evolve it into a full class structure as your program grows.
This feature was previewed in JDK 21 and is now a standard feature in JDK 25!