Modern Java

41. Unnamed Classes and Instance main

Unnamed classes (JEP 445/495) eliminate the boilerplate of public class ... { public static void main(String[] args) { ... } } for simple programs โ€” a single main() method in a file is enough.

Java 21 preview โ†’ Java 25 standard

Explanation

JEP 445 (Java 21 preview), refined in later JEPs through Java 25, allows you to write a simple Java program without wrapping it in a class declaration. The file itself is implicitly an unnamed class. The main method can be static or instance-based, and the String[] args parameter and public modifier are optional.

This dramatically lowers the barrier for beginners and scripting use cases. It is not a replacement for proper class-based programs โ€” it's a convenience feature for simple, top-level programs. The unnamed class cannot be referenced from other code (no name to import), cannot have a supertype, and cannot declare constructors.

Example

// UnnamedMain.java โ€” no class declaration needed (Java 21+ preview, Java 25 standard)
// Run with: java UnnamedMain.java  (or  java --enable-preview UnnamedMain.java in preview)

// Imports work normally
import java.util.List;

// Instance fields are allowed
String greeting = "Hello from an unnamed class!";

// Instance method
void sayHello(String name) {
    System.out.println(greeting + " " + name);
}

// The entry point โ€” no 'public static', no 'String[] args' required
void main() {
    sayHello("Alice");

    var numbers = List.of(1, 2, 3, 4, 5);
    numbers.stream()
           .filter(n -> n % 2 == 0)
           .forEach(System.out::println);
}

Sources