Unnamed Classes and Instance Main Methods
Unnamed Classes and Instance Main Methods (JEP 445) is a Preview feature introduced in Java 21. While it might sound technical, its goal is very simple: Make Java easier to learn and write for small programs.
The “Hello World” Barrier
For decades, the first thing a student sees when learning Java is this:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
This is a lot of “boilerplate” (clutter). A beginner immediately has questions:
- Why
public? - What is a
class? - Why
static? - What is
void? - What is
String[] args?
This complexity makes Java feel heavy for simple scripts or experiments compared to languages like Python or JavaScript.
The New, Simple Way
With Java 21, the language is getting out of your way. You can now write a valid program that looks like this:
void main() {
System.out.println("Hello, World!");
}
That’s it. No class declaration. No public. No static. No args.
Key Changes
1. Instance Main Methods
You no longer strictly need public static void main(String[] args).
- It doesn’t need to be
public. - It doesn’t need to be
static. - It doesn’t need
String[] argsif you aren’t using command-line arguments.
Java will now look for a void main() method and launch it.
2. Unnamed Classes
You noticed the code above didn’t have class HelloWorld { ... } wrapping it? When you write methods and fields at the top level of a file, Java automatically wraps them in an “unnamed class” for you.
This allows you to write scripts that focus purely on logic:
// Just fields and methods!
String greeting = "Hello";
String getMessage() {
return greeting + ", World!";
}
void main() {
System.out.println(getMessage());
}
“Gradual” Growth
The best part of this feature is that it is compatible with valid Java. As your program grows larger, you can easily wrap it in a class later. You aren’t learning a specific “dialect” of Java; you are just learning the core parts (methods, variables) first, and the organizational parts (classes, packages, access modifiers) later.
How to Run It
Since this is a Preview Feature in Java 21, you must explicitly enable it.
Compiling and Running:
javac --release 21 --enable-preview HelloWorld.java
java --enable-preview HelloWorld
Running directly (Source-Code Launch):
java --enable-preview --source 21 HelloWorld.java
This feature creates a smooth “on-ramp” for Java, making it accessible for beginners and concise for experts writing quick tools.