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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
