Java / Java 21 Interview Questions
What are Unnamed Classes and Instance Main Methods in Java 21 (Preview)?
JEP 445 (preview in Java 21) removes much of the ceremony required to write a simple Java program. It targets learning, scripting, and small utilities — not production application structure.
// Traditional Hello World — requires class declaration, static, String[] args
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
// Java 21 Preview — unnamed class, instance main, no args
void main() {
System.out.println("Hello, World!");
}
// The file is still named Main.java (or any name)
// Compile: javac --enable-preview --release 21 Main.java
// Run: java --enable-preview Main
// Top-level methods and fields are allowed
String greeting = "Hello";
void main() {
System.out.println(greeting + ", World!");
greet("Alice");
}
void greet(String name) {
System.out.println(greeting + ", " + name + "!");
}
// Main method signature flexibility:
// void main() -- new (no args, instance)
// static void main() -- no args, static
// static void main(String[]) -- traditionalThe launch protocol in JEP 445 checks for a valid main method in this order: first static void main(String[]) (traditional), then static void main(), then void main(String[]), then void main(). This ensures backward compatibility — existing programs are unaffected.
More Related questions...